How to add a value to nested list in json?

Question:

I have a json variable looks like this

json_data=

[
    {
        "authType": "ldap",
        "password": "",
        "permissions": [
            {
                "collections": [
                    "aks9099",
                    "aks9098"
                ],
                "project": "Central Project"
            }
        ],
        "role": "devSecOps",
        "username": "[email protected]"
    }
]

would like to add aks9100 to the collections
expected result should be looks like this

[
    {
        "authType": "ldap",
        "password": "",
        "permissions": [
            {
                "collections": [
                    "aks9099",
                    "aks9098",
                    "aks9100"
                ],
                "project": "Central Project"
            }
        ],
        "role": "devSecOps",
        "username": "[email protected]"
    }
]

thanks

Asked By: chin wooi Ng

||

Answers:

Here is a quick non-dynamic way to do this:

import json

json_path = '/Path/To/File.json'
# Open and read file
with open(json_path, 'r') as fin:
    json_data = json.load(fin)

# Open and write to file
with open(json_path, 'w') as fout:
    # Add str to nested list
    json_data[0]['permissions'][0]['collections'].append("aks9100")
    # Use write() and dumps() to maintain the json format
    fout.write(json.dumps(json_data, indent=4))

In the above I am assuming you need to update a json file. In the json data you have a list with a nested dictionary and another list nested in that dictionary. [0] gets the first item in the list and the dictionary keys return their respective values.

Answered By: Camden L

To add "aks9100" to this specific json variable you would need to use the following code:

import json

json_data[0]['permissions'][0]['collections'].append("aks9100")
Answered By: Blye
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.