0

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

3
  • The key "Honor" is down several levels in the structure. You will have to get there one by one. Commented Feb 6, 2023 at 2:12
  • Possible duplicate: stackoverflow.com/questions/70782902/… Commented Feb 6, 2023 at 2:14
  • temp = data['web']['all']['side']['Honor'] Commented Feb 6, 2023 at 2:16

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.