[英]How to format a list of nested dictionaries for writing to a file in a human readable form
我有一个大列表,其中列表的每个元素都是字典。 在字典中嵌套了另一个列表,该列表本身包含数百个键:值对。 我想将此列表写入文件,以便:
[
开头并以]
结尾我希望它看起来像这样:
[{
"id": "1",
"day": 20190928,
"layer": {
"some_value": "value",
"some_other_value": 2,
"some_value_int": 5,
"imageFormat": "image/png",
},
"elements": [
{
"httpStatusCode": 200,
"requestTime": 1553731321446,
"some_attribute": 143,
"some_binary_value": True,
},
{
"httpStatusCode": 200,
"requestTime": 1553731321446,
"some_attribute": 143,
"some_binary_value": True,
},
# and so on...
我觉得这一定是一项微不足道的任务,但有点迷茫。 这是我尝试过的:
for item in converted_data:
for key, value in item.items():
if type(value) == dict:
#Implement
pass
elif type(value) == list:
#Implement
pass
else:
outfile.write(" {} : {},\n".format(key, value))
但即使在完成它之前,我也发现这是一种错误的方法,会使这个简单的事情变得非常复杂。 我看过 SO 但没有找到与我的问题类似的问题。 那么,我该怎么做呢?
我不需要像我建议的那样成为文件。 我只需要它是人类和机器可读的。
对于如何解决此问题的任何建议,我将不胜感激。
import json
list_of_dicts # your list
data = json.dumps(list_of_dicts, indent = 4)
# write data to a file...
这将使用 4 个空格进行缩进,如果需要,将 4 更改为其他内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.