如何将 Python 字典打印为 JSON 格式?
programmingpythonserver side programming
使用 json Python 模块可以轻松地将 Python 字典显示为 JSON 格式。json 模块是一个 JSON 编码器/解码器。JSON 是 JavaScript 对象表示法,是一种轻量级的基于文本的开放标准,专为人类可读的数据交换而设计。JSON 格式由 Douglas Crockford 指定。它已从 JavaScript 脚本语言扩展而来。
将字典视为一组键:值对,要求键是唯一的(在一个字典内)。字典中的每个键都用冒号 (:) 与其值分隔,项目用逗号分隔,整个内容用花括号括起来。
让我们首先创建一个 Python 字典并获取所有值。在这里,我们在字典中包含了 4 个键值对并显示它们。产品、型号、单位 和 可用 是字典的键。除 Units 键外,所有键都具有字符串值 −
示例
# Creating a Dictionary with 4 key-value pairs myprod = { "Product":"Mobile", "Model": "XUT", "Units": 120, "Available": "Yes" } # Displaying the Dictionary print(myprod) # Displaying individual values print("Product = ",myprod["Product"]) print("Model = ",myprod["Model"]) print("Units = ",myprod["Units"]) print("Available = ",myprod["Available"])
输出
{'Product': 'Mobile', 'Model': 'XUT', 'Units': 120, 'Available': 'Yes'} Product = Mobile Model = XUT Units = 120 Available = Yes
上面,我们在包含产品信息的字典中显示了 4 个键值对。现在,我们将看到在 Python 中更新字典值的两种方法。现在,我们将字典设置为 JSON 格式。
使用 dumps() 方法将字典打印为 JSON 格式
json 模块的 dumps() 函数用于返回 Python 字典对象的 JSON 字符串表示形式。dumps() 的参数是字典 -
示例
import json # Creating a Dictionary with 4 key-value pairs myprod = { "Product":"Mobile", "Model": "XUT", "Units": 120, "Available": "Yes" } # Converting to JSON format myJSON = json.dumps(myprod) # Displaying the JSON format print("\nJSON format = ",myJSON);
输出
JSON format = {"Product": "Mobile", "Model": "XUT", "Units": 120, "Available": "Yes"}
使用 __str__(self) 方法将字典打印为 JSON 对象
__str___(self) 函数用于返回对象的字符串表示形式。我们在这里声明了一个类,并将其用作字符串表示形式,以将其转换为 json 对象 −
示例
import json # Creating a Dictionary myprod = { "Product":"Mobile", "Model": "XUT", "Units": 120, "Available": "Yes" } # Declared a class class myfunc(dict): def __str__(self): return json.dumps(self) myJSON = myfunc(myprod) print("\nJSON format = ",myJSON);
输出
JSON format = {"Product": "Mobile", "Model": "XUT", "Units": 120, "Available": "Yes"}
将字典打印到 JSON 数组中
数组可以转换为 JSON 对象。我们将在数组中设置键和值并使用 dump() 方法 −
示例
import json # Creating a Dictionary myprod = { "Product":"Mobile", "Model": "XUT", "Units": 120, "Available": "Yes" } # Keys and Values of a Dictionary in an array arr = [ {'key' : k, 'value' : myprod[k]} for k in myprod] # Displaying the JSON print("\nJSON format = ",json.dumps(arr));
输出
JSON format = [{"key": "Product", "value": "Mobile"}, {"key": "Model", "value": "XUT"}, {"key": "Units", "value": 120}, {"key": "Available", "value": "Yes"}]