📜  Python中的漂亮打印 JSON

📅  最后修改于: 2022-05-13 01:54:58.759000             🧑  作者: Mango

Python中的漂亮打印 JSON

JSON是一种用于存储和获取数据的 JavaScript 表示法。数据通常存储在 JSON、XML 或其他一些数据库中。它是一种完全独立于语言的文本格式。为了处理 JSON 数据, Python有一个名为json的内置包。

注意:有关详细信息,请参阅使用Python读取、写入和解析 JSON

漂亮的打印 JSON

每当使用Python中存在的内置模块“json”将数据转储到字典中时,显示的结果与字典格式相同。在这里,Pretty Print Json 的概念出现了,我们可以将加载的 JSON 显示为可呈现的格式。

示例 1:

# Write Python3 code here
   
import json
   
json_data = '[{"Employee ID":1,"Name":"Abhishek","Designation":"Software Engineer"},' \
            '{"Employee ID":2,"Name":"Garima","Designation":"Email Marketing Specialist"}]'
   
json_object = json.loads(json_data)
   
# Indent keyword while dumping the
# data decides to what level 
# spaces the user wants.
print(json.dumps(json_object, indent = 1))
   
# Difference in the spaces 
# near the brackets can be seen
print(json.dumps(json_object, indent = 3))

输出:

[
 {
  "Employee ID": 1,
  "Name": "Abhishek",
  "Designation": "Software Engineer"
 },
 {
  "Employee ID": 2,
  "Name": "Garima",
  "Designation": "Email Marketing Specialist"
 }
]
[
   {
      "Employee ID": 1,
      "Name": "Abhishek",
      "Designation": "Software Engineer"
   },
   {
      "Employee ID": 2,
      "Name": "Garima",
      "Designation": "Email Marketing Specialist"
   }
]

示例 2:假设我们想要漂亮地打印 JSON 文件中的数据。

JSON文件:

漂亮的打印 json

import json 
     
# Opening JSON file 
f = open('myfile.json',) 
     
# returns JSON object as  
# a dictionary 
data = json.load(f) 
     
print(json.dumps(data, indent = 1)
     
# Closing file 
f.close() 

输出:

{
 "emp1": {
  "name": "Lisa",
  "designation": "programmer",
  "age": "34",
  "salary": "54000"
 },
 "emp2": {
  "name": "Elis",
  "designation": "Trainee",
  "age": "24",
  "salary": "40000"
 }
}