python打印json_Python漂亮打印JSON

本文介绍了如何使用Python的json模块来格式化并漂亮地打印JSON数据。内容包括从JSON字符串和文件进行打印,并强调了json.dumps()方法的indent参数在控制缩进和美化输出中的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值