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 的文件,其中包含上述的字典数据。
使用缩进参数
使用方法dump()的缩进参数进行美观的打印。
示例
以下程序使用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
# 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"
}
现在的键是 按字母顺序排序 ,如上所示。
分隔符是一个额外的参数,可以使用它。在这里,你可以使用任何你喜欢的分隔符(”, “,”: “,”,”,”:”)。
将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.dumps()函数,该函数用于将任何可迭代对象转换为JSON格式。