我们可以使用Python json 模块漂亮地打印 JSON 数据。建议使用 json 模块来处理 JSON 文件。我们可以使用dumps()
方法来获取格式漂亮的 JSON 字符串。
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"
}
]
- 首先,我们使用 json.loads() 从 json 字符串创建 json 对象。
- json.dumps() 方法接受 json 对象并返回 JSON 格式的字符串。这
indent
参数用于定义格式化字符串的缩进级别。
让我们看看当我们尝试打印 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"
}
]
从输出中可以清楚地看出,我们必须传递缩进值才能将 JSON 数据转换为漂亮的打印格式。
- Python.org json.dumps() 文档
- 堆栈溢出问题