如何用Python打印JSON文件?
当前回答
def saveJson(date,fileToSave):
with open(fileToSave, 'w+') as fileToSave:
json.dump(date, fileToSave, ensure_ascii=True, indent=4, sort_keys=True)
它可以将其显示或保存到文件中。
其他回答
您可以在命令行上执行此操作:
python3 -m json.tool some.json
(正如问题评论中已经提到的,感谢@Kai Petzke提出的蟒蛇3建议)。
实际上,就命令行上的json处理而言,python不是我最喜欢的工具。对于简单漂亮的打印是可以的,但是如果你想操作json,它可能会变得过于复杂。您很快就需要编写一个单独的脚本文件,最终可能会得到键为u“somekey”(python unicode)的映射,这使得选择字段变得更加困难,并不会真正朝着漂亮打印的方向发展。
您也可以使用jq:
jq . some.json
你可以得到颜色作为奖励(而且更容易扩展)。
附录:关于一方面使用jq处理大型JSON文件,另一方面使用非常大的jq程序,评论中存在一些困惑。对于漂亮地打印由单个大型JSON实体组成的文件,实际限制是RAM。对于由单个真实世界数据数组组成的2GB文件的漂亮打印,漂亮打印所需的“最大驻留集大小”为5GB(无论使用jq 1.5还是1.6)。还要注意,在pip安装jq之后,可以在python中使用jq。
使用这个函数,不用担心,你必须再次记住你的JSON是str还是dict-看看漂亮的打印:
import json
def pp_json(json_thing, sort=True, indents=4):
if type(json_thing) is str:
print(json.dumps(json.loads(json_thing), sort_keys=sort, indent=indents))
else:
print(json.dumps(json_thing, sort_keys=sort, indent=indents))
return None
pp_json(your_json_string_or_dict)
使用json标准库模块读取数据后,使用pprint标准库模块显示解析的数据。例子:
import json
import pprint
json_data = None
with open('file_name.txt', 'r') as f:
data = f.read()
json_data = json.loads(data)
pprint.pprint(json_data)
输出将如下所示:
{'address': {'city': 'New York',
'postalCode': '10021-3100',
'state': 'NY',
'streetAddress': '21 2nd Street'},
'age': 27,
'children': [],
'firstName': 'John',
'isAlive': True,
'lastName': 'Smith'}
请注意,此输出不是有效的JSON;虽然它以良好的格式显示Python数据结构的内容,但它使用Python语法来实现。特别是,字符串(通常)用单引号括起来,而JSON需要双引号。要将数据重写为JSON文件,请使用pprint.pdf格式:
pretty_print_json = pprint.pformat(json_data).replace("'", '"')
with open('file_name.json', 'w') as f:
f.write(pretty_print_json)
使用pprint:https://docs.python.org/3.6/library/pprint.html
import pprint
pprint.pprint(json)
print()与pprint.pprint()比较
print(json)
{'feed': {'title': 'W3Schools Home Page', 'title_detail': {'type': 'text/plain', 'language': None, 'base': '', 'value': 'W3Schools Home Page'}, 'links': [{'rel': 'alternate', 'type': 'text/html', 'href': 'https://www.w3schools.com'}], 'link': 'https://www.w3schools.com', 'subtitle': 'Free web building tutorials', 'subtitle_detail': {'type': 'text/html', 'language': None, 'base': '', 'value': 'Free web building tutorials'}}, 'entries': [], 'bozo': 0, 'encoding': 'utf-8', 'version': 'rss20', 'namespaces': {}}
pprint.pprint(json)
{'bozo': 0,
'encoding': 'utf-8',
'entries': [],
'feed': {'link': 'https://www.w3schools.com',
'links': [{'href': 'https://www.w3schools.com',
'rel': 'alternate',
'type': 'text/html'}],
'subtitle': 'Free web building tutorials',
'subtitle_detail': {'base': '',
'language': None,
'type': 'text/html',
'value': 'Free web building tutorials'},
'title': 'W3Schools Home Page',
'title_detail': {'base': '',
'language': None,
'type': 'text/plain',
'value': 'W3Schools Home Page'}},
'namespaces': {},
'version': 'rss20'}
我认为最好先解析json,以避免错误:
def format_response(response):
try:
parsed = json.loads(response.text)
except JSONDecodeError:
return response.text
return json.dumps(parsed, ensure_ascii=True, indent=4)