python打印json
We can use the Python json module to pretty-print the JSON data.
我们可以使用Python json模块漂亮地打印JSON数据。
The json module is recommended to work with JSON files. We can use the dumps()
method to get the pretty formatted JSON string.
建议将json模块与JSON文件一起使用。 我们可以使用dumps()
方法获取格式精美的JSON字符串。
1. Python漂亮打印JSON字符串 (1. Python Pretty Print JSON String)
import json
json_data = '[{"ID":10,"Name":"Pankaj","Role":"CEO"},' \
'{"ID":20,"Name":"David Lee","Role":"Editor"}]'
json_object = json.loads(json_data)
json_formatted_str = json.dumps(json_object, indent=2)
print(json_formatted_str)
Output:
输出:
[
{
"ID": 10,
"Name": "Pankaj",
"Role": "CEO"
},
{
"ID": 20,
"Name": "David Lee",
"Role": "Editor"
}
]
- First of all, we are using json.loads() to create the json object from the json string. 首先,我们使用json.loads()从json字符串创建json对象。
- The json.dumps() method takes the json object and returns a JSON formatted string. The
indent
parameter is used to define the indent level for the formatted string. json.dumps()方法接受json对象,并返回JSON格式的字符串。indent
参数用于定义格式化字符串的缩进级别。
2. Python漂亮打印JSON文件 (2. Python Pretty Print JSON File)
Let’s see what happens when we try to print a JSON file data. The file data is saved in a pretty printed format.
让我们看看当尝试打印JSON文件数据时会发生什么。 文件数据以漂亮的打印格式保存。

Json Pretty Printed File
杰森漂亮的打印文件
import json
with open('Cars.json', 'r') as json_file:
json_object = json.load(json_file)
print(json_object)
print(json.dumps(json_object))
print(json.dumps(json_object, indent=1))
Output:
输出:
[{'Car Name': 'Honda City', 'Car Model': 'City', 'Car Maker': 'Honda', 'Car Price': '20,000 USD'}, {'Car Name': 'Bugatti Chiron', 'Car Model': 'Chiron', 'Car Maker': 'Bugatti', 'Car Price': '3 Million USD'}]
[{"Car Name": "Honda City", "Car Model": "City", "Car Maker": "Honda", "Car Price": "20,000 USD"}, {"Car Name": "Bugatti Chiron", "Car Model": "Chiron", "Car Maker": "Bugatti", "Car Price": "3 Million USD"}]
[
{
"Car Name": "Honda City",
"Car Model": "City",
"Car Maker": "Honda",
"Car Price": "20,000 USD"
},
{
"Car Name": "Bugatti Chiron",
"Car Model": "Chiron",
"Car Maker": "Bugatti",
"Car Price": "3 Million USD"
}
]
It’s clear from the output that we have to pass the indent value to get the JSON data into a pretty printed format.
从输出中很明显,我们必须传递缩进值以将JSON数据转换为漂亮的打印格式。
参考资料 (References)
翻译自: https://www.journaldev.com/33302/python-pretty-print-json
python打印json