print(pretty_json_str) 1. 运行以上代码,就能够将格式化的JSON字符串输出到控制台。 示例代码 下面是完整的示例代码: importjson# 定义一个字典data={"name":"Alice","age":20,"city":"New York"}# 将字典转换为JSON字符串json_str=json.dumps(data)# 将JSON字符串转换为Python对象python_obj=json.loads...
It’s clear from the output that we have to pass the indent value to get the JSON data into a pretty printed format.
Pretty printing JSON String in Python Execute import json ugly_json = '[ {"Customer": 1, "name": "Alice", "country": ["Spain", "Madrid"]}, \ {"Customer": 2, "name": "Jack", "country": ["UK", "London"]} ]' parsed_json = json.loads(ugly_json) pretty_json = json.dumps...
To make json.tool complain, you need to invalidate your JSON document. You can make the JSON data of dog_friend.json invalid by removing the comma (,) between the key-value pairs: JSON dog_friend.json 1{ 2 "name": "Mitch" 3 "age": 6.5 4} After saving dog_friend.json, run ...
{"a": 23,"b": 42,"c": 12648430}#Note this only works with dicts containing#primitive types (check out the "pprint" module):>>> json.dumps({all:'yup'}) TypeError: keys must be a string In most cases I'd stick to the built-in "pprint" module though :-)...
这里可以看到虽然textfsm输出的内容为JSON格式,但是依然不具备可读性。为了将内容更美观地打印出来,这里我们可以用到Python另外一个很强大的内置库:pprint,pprint全称是pretty printer,它的功能是将各种数据结构更美观地输出。这里我们将netmiko3_1.py的代码稍作修改,在第二行加上from pprint import pprint,在最后一行将...
1.Create a filenamedmy_file.jsonwith the following contents: {"employees":[{"name":"bob","sector":"devops"},{"name":"alice","sector":"infosec"}]} 2. The code below demonstrates how to import and PrettyPrint a JSON file in Python: ...
print(json.dumps(json_object, indent=2)) [ { "model number": "RX100", "customer": "Adam", "Company": "Samsung" }, { "model number": "FH450", "customer": "Paul", "Company": "Lenevo" } ] Pretty Print a JSON file on the command line ...
json.dumps()function serializes the givenobjto a JSON formattedstr. We need to give a positive integer to the keyword parameterindentin thejson.dumps()function to pretty print theobjwith the given indent level. Ifidentis set to be 0, it will only insert new lines. ...
# json.dump() 先序列化,再写入文件 li=[11,22,33] json.dump(li,open('db','w')) # json.load() 读取文件反序列化 l=json.load(open('db','r')) print(l,type(l)) pickle模块 pickple只有python才能用,用于复杂类型的序列化,(如果是序列化一个对象,在别的模块中反序列化的时候一定要导入该...