添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

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文件数据时会发生什么。 文件数据以漂亮的打印格式保存。

[{'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值。