Python Pretty Print JSON

我们可以使用 Python json 模块来非常打印 JSON 数据。

Python Pretty Print JSON 字符串

 1import json
 2
 3json_data = '[{"ID":10,"Name":"Pankaj","Role":"CEO"},' \
 4            '{"ID":20,"Name":"David Lee","Role":"Editor"}]'
 5
 6json_object = json.loads(json_data)
 7
 8json_formatted_str = json.dumps(json_object, indent=2)
 9
10print(json_formatted_str)

输出:

 1[
 2  {
 3    "ID": 10,
 4    "Name": "Pankaj",
 5    "Role": "CEO"
 6  },
 7  {
 8    "ID": 20,
 9    "Name": "David Lee",
10    "Role": "Editor"
11  }
12]
  • 首先,我们使用 json.loads() 从 json 字符串中创建 json 对象
  • json.dumps() 方法取代 json 对象并返回 JSON 格式化字符串。

Python Pretty 打印 JSON 文件

让我们看看当我们尝试打印 JSON 文件数据时会发生什么。

Json Pretty Printed File

 1import json
 2
 3with open('Cars.json', 'r') as json_file:
 4    json_object = json.load(json_file)
 5
 6print(json_object)
 7
 8print(json.dumps(json_object))
 9
10print(json.dumps(json_object, indent=1))

输出:

 1[{'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'}]
 2[{"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"}]
 3[
 4 {
 5  "Car Name": "Honda City",
 6  "Car Model": "City",
 7  "Car Maker": "Honda",
 8  "Car Price": "20,000 USD"
 9 },
10 {
11  "Car Name": "Bugatti Chiron",
12  "Car Model": "Chiron",
13  "Car Maker": "Bugatti",
14  "Car Price": "3 Million USD"
15 }
16]

从输出中可以看出,我们必须传输入值以将JSON数据输入到一个非常好的打印格式。

参考

Published At
Categories with 技术
Tagged with
comments powered by Disqus