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"
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文件数据时会发生什么。 文件数据以漂亮的打印格式保存。
[{'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
python打印jsonWe 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 g...
##描述:让你的 json 文件更漂亮###例如:
[{'a':{'list':[1,2,3],'b':'c'},{'hi':'hello'}]
will be processed and pretty json will look like
'a':{
'list':[1,2,3],
'b':'c'
'hi':'hello'
用法: 将 prettfy_json.py 文件复制到 json 文件所在的目录中运行: python prettyjson.py yourfilename.json
*json file will be pretified*
from pprint import pprint
data = {"name": "Tom", "age": 23, "gender": "man"}
print(data)
# {'name': 'Tom', 'age': 23, 'gender': 'man'}
pprin
其中,json.loads()方法将JSON字符串转换为Python对象,json_obj['name']和json_obj['age']分别获取了JSON数据中的name和age的value值。
如果JSON数据中包含嵌套的数据结构,可以使用类似的方法来获取其中的value值。