skip to Main Content

Trying to append to a nested json file

My goal is to append some values to a JSON file.

Here is my original JSON file

{
    "web": {
        "all": {
          "side": {
            "tags": [
              "admin"
            ],
            "summary": "Generates",
            "operationId": "Key",
            "consumes": [],
            "produces": [
              "application/json"
            ],
            "responses": {
              "200": {
                "description": "YES",
                "schema": {
                  "type": "string"
                }
              }
            },
            "Honor": [
              {
                "presidential": []
              }
            ]
          }
        }

    }
}

It is my intention to add two additional lines inside the key "Honor", with the values "Required" : "YES" and "Prepay" : "NO". As a result of appending the two values, I will have the following JSON file.

{
    "web": {
        "all": {
          "side": {
            "tags": [
              "admin"
            ],
            "summary": "Generates",
            "operationId": "Key",
            "consumes": [],
            "produces": [
              "application/json"
            ],
            "responses": {
              "200": {
                "description": "YES",
                "schema": {
                  "type": "string"
                }
              }
            },
            "Honor": [
              {
                "presidential": [],
                "Required" : "YES",
                "Prepay"   : "NO"
              }
            ]
          }
        }

    }
}

Below is the Python code that I have written

import json
def write_json(data,filename ="exmpleData.json"):
    with open(filename,"w") as f:
        json.dump(data,f,indent=2)
with open ("exmpleData.json") as json_files:
    data= json.load(json_files)
    temp = data["Honor"]
    y = {"required": "YES","type": "String"}
    temp.append(y)
write_json(data)

I am receiving the following error message:

** temp = data["Honor"] KeyError: ‘Honor’
**
I would appreciate any guidance that you can provide to help me achieve my goal. I am running Python 3.7

2

Answers


  1. 'Honor' is deeply nested in other dictionaries, and its value is a 1-element list containing a dictionary. Here’s how to access:

    import json
    
    def write_json(data, filename='exmpleData.json'):
        with open(filename, 'w') as f:
            json.dump(data, f, indent=2)
    
    with open('exmpleData.json') as json_files:
        data = json.load(json_files)
        # 'Honor' is deeply nested in other dictionaries
        honor = data['web']['all']['side']['Honor']
        # Its value is a 1-element list containing another dictionary.
        honor[0]['Required'] = 'YES'
        honor[0]['Prepay'] = 'NO'
    
    write_json(data)
    
    Login or Signup to reply.
  2. I’d recommend that you practice your fundamentals a bit more since you’re making many mistakes in your data structure handling. The good news is, your JSON load/dump is fine.

    The cause of your error message is that data doesn’t have an "Honor" property. Data only has a "web" property, which contains "all" which contains "side" which contains "Honor", which contains an array with a dictionary that holds the properties you are trying to add to. So you want to set temp with temp = data['web']['all']['side']['Honor'][0]

    You also cannot use append on python dictionaries. Instead, check out dict.update().

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search