如何在Python中寫入JSON?


在這篇文章中,我們將學習在Python中寫入JSON的不同方法。

轉換規則

將Python物件轉換為JSON資料時,dump()方法遵循以下轉換規則:

Python

JSON

dict

object

list, tuple

array

str

string

int, float

number

True

true

False

false

None

null

將字典寫入JSON檔案

json.dump()函式的作用是將Python物件整理成JSON格式的流,並寫入指定的檔案。

語法

dump(obj, fp, *, skipkeys=False,
   check_circular=True, allow_nan=True,
   indent=None, separators=None, default=None,
   sort_keys=False, **kw)

引數

  • obj − obj 是一個物件,它被整理成JSON格式的流。

  • fp − fp 也稱為檔案物件,用於儲存JSON資料。

  • skipkeys − 預設值為False。它忽略字典中不是基本型別的鍵。否則,它將丟擲TypeError。

  • check_circular − 預設值為True。它的主要任務是為容器型別執行迴圈引用檢查。這有時會導致OverflowError。

  • allow_nan − 預設值為True。如果為False,則序列化超出範圍的浮點值將導致ValueError。它預設使用JavaScript等效項,例如-NaN、Infinity、-Infinity。

  • indent − 用於以指定的縮排格式進行漂亮的列印。

  • separators − 這些是JSON中使用的分隔符。

  • default − 當物件無法序列化時呼叫此函式。它要麼返回物件的JSON編碼版本,要麼丟擲TypeError。如果沒有指定型別,則預設丟擲TypeError。

  • sort_keys − 預設值為False。如果為True,則字典的輸出將按鍵排序。

示例

以下程式使用json.dump()函式將給定的字典轉換為JSON檔案:

# importing json module
import json

# creating a dictionary
inputDict = {
   "website": "Tutorialspoint",
   "authorName": "xyz",
   "Age": 25,
   "Address": "hyderabad",
   "pincode":"503004"
}

# opening a JSON file in write mode
with open('outputfile.json', 'w') as json_file:

   # writing the dictionary data into the corresponding JSON file
   json.dump(inputDict, json_file)

輸出

執行上述程式將生成以下輸出:

{"website": "Tutorialspoint", "authorName": "xyz", "Age": 25, "Address": "hyderabad", "pincode": "503004"}

將建立一個名為outputfile.json的檔案,其中包含上述字典資料。

使用Indent引數

使用dump()方法的indent引數進行漂亮的列印。

示例

以下程式使用json.dump()函式和indent引數將給定的字典轉換為具有縮排的漂亮JSON檔案:

# importing JSON module
import json

# creating a dictionary
inputDict = {
   "website": "Tutorialspoint",
   "authorName": "xyz",
   "Age": 25,
   "Address": "hyderabad",
   "pincode":"503004"
}

# opening a JSON file in write mode
with open('outputfile.json', 'w') as json_file:

   # writing the dictionary data into the corresponding JSON file
   # by adding indent parameter to make it attractive with proper indentation
   json.dump(inputDict, json_file, indent=5)

輸出

執行上述程式將生成以下輸出:

{
   "website": "Tutorialspoint",
   "authorName": "xyz",
   "Age": 25,
   "Address": "hyderabad",
   "pincode": "503004"
}

將建立一個名為outputfile.json的檔案,其中包含上述字典資料,並具有適當的縮排,使其更美觀。

對JSON中的鍵進行排序

我們可以使用sort_keys = True引數按字母順序對字典的鍵進行排序。

以下程式使用json.dump()函式和sort_keys引數將給定的字典轉換為具有縮排和排序鍵的JSON檔案:

# importing JSON module
import json

# creating a dictionary
inputDict = {
   "website": "Tutorialspoint",
   "authorName": "xyz",
   "Age": 25,
   "Address": "hyderabad",
   "pincode":"503004"
}

# opening a JSON file in write mode
with open('outputfile.json', 'w') as json_file:

   # writing the dictionary data into the corresponding JSON file
   # indent parameter- to make it attractive with proper indentation
   # sort_keys- sorts the dictionary keys alphabetically
   json.dump(inputDict, json_file, indent=5, sort_keys=True)

輸出

{
   "Address": "hyderabad",
   "Age": 25,
   "authorName": "xyz",
   "pincode": "503004",
   "website": "Tutorialspoint"
}

如上所示,鍵現在按字母順序排序

Separators是可以使用的附加引數。在這裡,您可以使用任何您喜歡的分隔符(", ",": ",",",":")。

將Python列表轉換為JSON

示例

以下程式使用dumps()函式將Python列表轉換為JSON字串:

# importing JSON module
import json

# input list
inputList = [2, 4, 6, 7]

# converting input list into JSON string using dumps() function
jsonString = json.dumps(inputList)

# printing the resultant JSON string
print(jsonString)

# printing the type of resultant JSON string
print(type(jsonString))

輸出

[2, 4, 6, 7]
<class 'str'>

將Python字典列表轉換為JSON

示例

以下程式使用dumps()函式將Python字典列表轉換為JSON字串。

# importing json module
import json

# input list of dictionaries
list_dict = [{'x':10, 'y':20, 'z':30}, {'p':40, 'q':50}]

# converting list of dictionaries into json string
jsonData = json.dumps(list_dict)

# printing the JSON data
print(jsonData)

輸出

[{"x": 10, "y": 20, "z": 30}, {"p": 40, "q": 50}]

將Python列表的列表轉換為JSON

示例

以下程式使用dumps()函式將Python列表的列表轉換為JSON字串:

# importing JSON module
import json

# input list of lists
list_of_list = [[{'x':10, 'y':20, 'z':30}], [{'p':40, 'q':50}]]

# converting a list of list into JSON string
jsonString = json.dumps(list_of_list)

# printing the resultant JSON string
print(jsonString)

輸出

[[{"x": 10, "y": 20, "z": 30}], [{"p": 40, "q": 50}]]

結論

本文包含各種將各種資料格式轉換為JSON檔案、JSON字串等的技巧。還深入介紹了用於將任何形式的可迭代物件轉換為JSON的json.dumps()。

更新於:2023年1月16日

467 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.