简体   繁体   中英

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, 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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