Home > Enterprise >  Load from .json file, sort data according to value then save it to same .json file
Load from .json file, sort data according to value then save it to same .json file

Time:03-01

The JSON file I have:

[{
"key_a": "value",
"key_b": [{
        "key_a": "c",
        "key_b": null
    },
    {
        "key_a": "b",
        "key_b": null
    }]
}]

The format I want:

[{
    "key_a": "value",
    "key_b": [{
            "key_a": "b",
            "key_b": null
        },
        {
            "key_a": "c",
            "key_b": null
        }]
}]

How can I sort child elements according to the value of key (for example according to 'key_a') then save it to the source JSON file from where data was loaded?

What I have in mind is something like this:

def read_json_file():
    with open(filename) as file:
        var = json.load(file)
    file.close()

def sort_json_var():
    ...

def write_json_file():
    with open (filename, 'w') as file:
        json.dump(data, file, indent=4)
    file.close()

CodePudding user response:

Python's builtin function sorted can do this. If var is your loaded json file (you probably want to pass it in to sort_json_var), then

sorted(var[0]["key_b"], key=lambda x:x["key_a"])

will return the inner part of what you want, as long as every element in it has key_a. Then all that's left is to assign that result back to var[0]["key_b"].

  • Related