Python json.dumps() 方法:完整指南
JSON 是一种方便的数据交易所格式,受 JavaScript 影响。 JSON 通常是字符串或文本格式,代表 JavaScript Object Notation。
要将 Python 对象编码或转换为 JSON 字符串,请使用 json.dumps() 方法。 这
Python json.dumps()
json.dumps() 是一个内置的 Python 函数,可以将任何数据编码为 JSON,该操作称为 json 编码。 json.dumps() 函数将字典对象转换为 JSON 字符串数据格式。
句法
json.dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)
参数
obj:它将 obj 序列化为 JSON 格式的流。
skipkeys:skipkeys 的默认参数为 False,但如果为 True,则将跳过非基本类型(str、int、float、bool、None)的 dict 键,而不是引发 TypeError。
ensure_ascii:ensure_ascii 的默认值为 True,确保输出所有传入的非 ASCII 字符都转义。
check_circular:check_circular的默认值为True,如果为False,则跳过容器类型的循环引用检查,循环引用会导致OverflowError。
allow_nan:check_circular 的默认值为 True,如果为 False,则在 JSON 规范中严格默认序列化超出范围的浮点值(nan、inf、-inf)将是 ValueError。
缩进:
- 如果缩进是非负整数或字符串,则 JSON 数组元素和对象成员将使用该缩进级别进行漂亮打印。
- 缩进级别 0、负数或“”只会插入新行。 无(默认)选择最紧凑的表示。
- 正整数缩进每级缩进许多空格。 如果缩进是一个字符串(例如“\t”),则该字符串用于缩进每个级别。
分隔符:如果指定,分隔符应该是 (item_separator, key_separator) 元组。 如果缩进为 None,则默认为 (‘, ‘, ‘: ‘),否则为 (‘, ‘, ‘: ‘)。 要获得最紧凑的 JSON 表示,您应该指定 (‘, ‘, ‘:’) 来修剪空白。
默认值:如果指定,默认值应该是为无法序列化的对象调用的函数。 它应该返回对象的 JSON 可编码版本或引发 TypeError。 如果未指定,则引发 TypeError。
sort_keys:sort_keys参数值默认为False,但如果为true,那么字典的输出将按key排序。
例子
编写以下代码来演示该 json.dumps() 方法。
import json # Creating a dictionary dict = {'Name': 'Mandalorian', 'Season': 'Two', 'Episode': 'First'} # Converts input dict to string and saves it in json_string json_string = json.dumps(dict) print('Equivalent json string of input dictionary:', json_string) # Checking type of object returned by json.dumps() print(type(json_string))
输出
Equivalent json string of input dictionary: {"Name": "Mandalorian", "Season": "Two", "Episode": "First"}
您可以看到输出是字典中的 json 字符串。
在 json.dumps() 中将 skipkeys 传递给 True
如果您在 json.dumps() 方法中传递 skipkeys = True,则跳过不属于基本数据类型的键。 例如,list、tuple 或 set 不是基本数据类型,而 integer、string 和 boolean 是基本数据类型。
# app.py import json # Creating a dictionary dict = { ('x', 'y', 'z'): 'Elder Wand', 2: 'Expecto', 3: 'Patronum', 4: 'Avada', 5: 'Kedavra' } # Converts input dictionary into string and stores it in json_string json_string = json.dumps(dict, skipkeys=True) print('Equivalent json string of input dictionary:', json_string) # Checking type of object returned by json.dumps print(type(json_string))
输出
Equivalent json string of input dictionary: {"2": "Expecto", "3": "Patronum", "4": "Avada", "5": "Kedavra"}
可以看到字典的第一个键是一个元组,不是基本的数据类型。 这就是为什么在输出中会跳过它。
传递超出范围的浮点值
要传递超出范围的浮点值,请使用 float() 方法。 在字典中定义 float(‘nan’) 值并将 allow_nan = True 传递给 dumps() 方法。
# app.py import json # Creating a dictionary dict = { ('x', 'y', 'z'): 'Elder Wand', 2: 'Expecto', 3: 'Patronum', 4: float('nan') } # Converts input dictionary into string and stores it in json_string json_string = json.dumps(dict, skipkeys=True, allow_nan=True) print('Equivalent json string of input dictionary:', json_string) # Checking type of object returned by json.dumps print(type(json_string))
输出
Equivalent json string of input dictionary: {"2": "Expecto", "3": "Patronum", "4": NaN}
将缩进参数传递给 json.dumps()
如果您将缩进作为参数传递,它将返回缩进的字符串。
# app.py import json # Creating a dictionary dict = { ('x', 'y', 'z'): 'Elder Wand', 2: 'Expecto', 3: 'Patronum', 4: float('nan') } # Converts input dictionary into string and stores it in json_string json_string = json.dumps(dict, skipkeys=True, allow_nan=True, indent=4) print('Equivalent json string of input dictionary:', json_string) # Checking type of object returned by json.dumps print(type(json_string))
输出
Equivalent json string of input dictionary: { "2": "Expecto", "3": "Patronum", "4": NaN }
对于 json 漂亮打印,将参数 ‘indent’ 传递给 json.dumps() 函数。
传递分隔符
如果你指定了分隔符,它应该返回一个 (item_separator, key_separator) 元组,并且项目之间用 ‘.’ 分隔。 键值用’=’分隔。
import json # Creating a dictionary dict = { ('x', 'y', 'z'): 'Elder Wand', 2: 'Expecto', 3: 'Patronum', 4: float('nan') } # Converts input dictionary into string and stores it in json_string json_string = json.dumps(dict, skipkeys=True, allow_nan=True, indent=4, separators=(". ", " = ")) print('Equivalent json string of input dictionary:', json_string) # Checking type of object returned by json.dumps print(type(json_string))
输出
Equivalent json string of input dictionary: { "2" = "Expecto". "3" = "Patronum". "4" = NaN }
订购结果
json.dumps() 方法有一个名为 sort_keys() 的参数,用于对结果中的键进行排序。
import json # Creating a dictionary dict = { 11: 'Elder Wand', 21: 'Expecto', 13: 'Patronum', 41: float('nan') } # Converts input dictionary into string and stores it in json_string json_string = json.dumps(dict, skipkeys=True, allow_nan=True, indent=4, separators=(". ", " = "), sort_keys=True) print('Equivalent json string of input dictionary:', json_string) # Checking type of object returned by json.dumps print(type(json_string))
输出
Equivalent json string of input dictionary: { "11" = "Elder Wand". "13" = "Patronum". "21" = "Expecto". "41" = NaN }
结论
json.dumps() 函数创建一个 json 对象。 json.dump() 方法使用 Python 的文件 I/O 创建一个 JSON 文件。 json.dumps() 方法将 Python 对象转换为 json 字符串。 json.loads() 函数解码 Python 字典中的 JSON 字符串。
而已。
也可以看看
Python json.load()
Python 字典到 json
Python json 到 dict
帖子 Python json.dumps() 方法:完整指南首先出现在 AppDividend 上。