📜  Python-Json 4: 如何使Json数据格式更易读

📅  最后修改于: 2020-08-29 02:23:16             🧑  作者: Mango

在之前章节中,我们学习了如何保存Json数据到文件

然后,在保存后的文件虽然是json文件,但是数据格式杂乱,很不易于阅读。在这种情况下,就需要我们json数据格式更易于阅读。因此,我们这节介绍PrettyPrinted方法。

在Python中需要JSON PrettyPrinting的场景:

  • 将PrettyPrinted JSON格式的数据写入文件
  • Prettyprint JSON文件:假设您有一个巨大且未正确缩进的JSON文件,并且您想对其进行漂亮打印。
  • Prettyprint JSON格式的字符串。

下图简单介绍方法的效果:

将PrettyPrinting的JSON数据写入文件

在实际情况下,我们处理大量的JSON数据。当我们将JSON数据写入文件时,我们必须确保JSON数据可读且组织良好,因此无论使用哪种格式的数据,都可以更好地理解JSON的结构。

使用json.dumps()方法,我们可以将prettyprinted JSON写入文件中。该方法提供以下参数来格式化的写入JSON数据。

indent参数指定在一行的开头使用的空间。我们可以使用json.dump()的indent参数来指定缩进值。默认情况下,当您将JSON数据写入文件时,Python不会使用缩进,而是将所有数据写入一行,这是不可读的。

separator参数:可以指定JSON键和值之间的任何分隔符。默认分隔符为(', ', ': ')。例如,如果指定分隔符(例如)(', ', ' : '),则JSON将看起来像这样。

sort_keys用于按字母顺序对JSON键进行排序的 参数。

import json

print("Writing Indented and Pretty-printed JSON formatted data into a file")

student = {
    "id": 1,
    "name": "dong",
    "class": 9,
    "attendance": 75,
    "subjects": ["English", "Geometry"],
    "email": "imango@qq.com"
}

with open("studentWithoutPrettyPrint.json", "w") as write_file:
    json.dump(student, write_file)
print("Done writing JSON data into file without Pretty Printing it")

with open("studentWithPrettyPrint1.json", "w") as write_file:
    json.dump(student, write_file, indent=4)
print("Done writing PrettyPrinted JSON data into file with indent=4")

with open("studentWithPrettyPrint2.json", "w") as write_file:
    json.dump(student, write_file, indent=0)
print("Done writing PrettyPrinted JSON data into file with indent=0")

with open("studentWithPrettyPrint3.json", "w") as write_file:
    json.dump(student, write_file, indent=4, sort_keys=True)
print("Done writing Sorted and PrettyPrinted JSON data into file")

我们看看第一个,直接保存后的文件:

我们看看第二个,indent=4保存后的文件:

我们看看第三个,indent=0保存后的文件:

我们看看第三个,排序后保存后的文件:

记得:

如果indent是非负整数或字符串,则JSON数组元素和对象成员将使用该缩进级别进行漂亮打印。例如,当我们指定indent = 4时,Python使用四个空格进行缩进。

缩进级别为0,为负或””仅插入换行符。无(默认)选择最紧凑的表示形式。使用正整数缩进会使每个级别缩进多个空格。如果indent是字符串(例如\t),则该字符串用于缩进每个级别。

调整从文件load的JSON数据

假设您有一个不正确缩进的JSON文件,并且想要对其格式调整。

我们需要执行以下步骤:

  • 首先使用json.load()方法读取JSON文件。
  • 通过指定缩进和分隔符,可使用json.dumps()方法正确打印JSON。该json.dumps()方法以字符串格式返回prettyprinted JSON数据。
    打印最终的JSON。
import json

with open("./student.json", "r") as read_file:
    print("Read JSON file")
    student = json.load(read_file)

    print("Before Pretty Printing JSON Data")
    print(student)

    print("\n")

    PrettyJson = json.dumps(student, indent=4, separators=(',', ': '), sort_keys=True)
    print("Displaying Pretty Printed JSON Data")
    print(PrettyJson)

结果如下:

Read JSON file

Before Pretty Printing JSON Data
{'id':1,'name':'Jessa Duggar','class':9,'出席':75,'subjects':['English','Geometry','Physics','World History'] ,“电子邮件":“ jess@example.com"}

Displaying Pretty Printed JSON Data
{
“出勤":75,
“类别":9
“ email":“ jess@example.com",
“ id":1
“ name":“ Jessa Duggar",
“主题":[
“英语",
“几何",
“物理",
“世界史"
]
}

使用pprint模块格式化打印JSON

pprint模块提供了“漂亮打印”任何Python数据结构的功能。现在,让我们看看如何使用该pprint模块漂亮地打印JSON数据。

pprint.pprint()函数在已配置的流上打印JSON的格式化表示形式,后跟换行符

  • 首先通过配置缩进和宽度值构造一个PrettyPrinter实例。另外,设置compact=False
  • 使用json.load()方法读取JSON文件。
  • 将JSON数据传递给pprint.pprint()函数
import json
import pprint

with open("studentWithoutPrettyPrint.json", "r") as read_file:
    print("Read JSON file")
    student = json.load(read_file)

    print("Before Pretty Printing JSON Data")
    print(student)

    print("\n")

# construct PrettyPrinter first
pp = pprint.PrettyPrinter(indent=4, width=80, compact=False)

print("Pretty Printing JSON Data using pprint module")
pp.pprint(student)

结果显示如下:

Read JSON file
Before Pretty Printing JSON Data
{'id': 1, 'name': 'dong', 'class': 9, 'attendance': 75, 'subjects': ['English', 'Geometry'], 'email': 'imango@qq.com'}


Pretty Printing JSON Data using pprint module
{   'attendance': 75,
    'class': 9,
    'email': 'imango@qq.com',
    'id': 1,
    'name': 'dong',
    'subjects': ['English', 'Geometry']}

注意:仅使用打印在控制台上显示JSON数据。切勿使用其输出将JSON写入文件。

使用命令行如何格式化打印Json数据

有些时候我们不得不命令行来打印出Json数据。

Python提供了json.tool模块,用于从命令行验证和漂亮地打印JSON对象。我们可以使用其模块的命令行界面执行以下任务。

命令如下:

python -m json.tool filePath

演示结果输出:

{
    "id": 1,
    "name": "dong",
    "class": 9,
    "attendance": 75,
    "subjects": [
        "English",
        "Geometry"
    ],
    "email": "imango@qq.com"
}

与此同时,也可以格式化的讲Jsons数据重定向到新的文件;

python -m json.tool oriFileName newFile.json

 

——–>>>>>