简体   繁体   English

如何格式化嵌套字典列表以以人类可读的形式写入文件

[英]How to format a list of nested dictionaries for writing to a file in a human readable form

I have a large list where each element of the list is a dictionary.我有一个大列表,其中列表的每个元素都是字典。 In the dictionary there is nested another list which itself contains hundreds of key:value pairs.在字典中嵌套了另一个列表,该列表本身包含数百个键:值对。 I would like to write this list to a file so that:我想将此列表写入文件,以便:

  1. it is nicely formatted (human-readable).它的格式很好(人类可读)。 different "levels" of the file are differently indented文件的不同“级别”的缩进不同
  2. it is still a list (ie the file starts with [ and ends with ]它仍然是一个列表(即文件以[开头并以]结尾

I'd like it to look something like this:我希望它看起来像这样:

[{
    "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...

I feel like it must be a trivial task but am a bit lost.我觉得这一定是一项微不足道的任务,但有点迷茫。 This is what I have tried:这是我尝试过的:

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))

But even before finishing it I see it is a wrong approach that would make something this simple very complicated.但即使在完成它之前,我也发现这是一种错误的方法,会使这个简单的事情变得非常复杂。 I have looked at SO but didn't find questions similar to my problem.我看过 SO 但没有找到与我的问题类似的问题。 So, how should I do this?那么,我该怎么做呢?

I don't need to be the file to be exactly like I suggested.我不需要像我建议的那样成为文件。 I just need it to be both human- and machine-readable.我只需要它是人类和机器可读的。

I will be grateful for any suggestions as to how to solve this.对于如何解决此问题的任何建议,我将不胜感激。

import json


list_of_dicts  # your list

data = json.dumps(list_of_dicts, indent = 4)

# write data to a file...

This will use 4 spaces for indentation, change 4 to something else if you want.这将使用 4 个空格进行缩进,如果需要,将 4 更改为其他内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM