Vaishali Ravindran
Vaishali Ravindran

Reputation: 1

How to add an new value to an existing json array?

My json structure is like this:

{
    "intents": [
        {
            "tag": "greeting",
            "patterns": [
                "Hi there",
                "How are you",
                "Is anyone there?",
                "Hey",
                "Hola",
                "Hello",
                "Good day"
            ],
            "responses": [
                "Hello, thanks for asking",
                "Good to see you again",
                "Hi there, how can I help?"
            ],
            "context": [""]
        },

My intention to append a new pattern or response under this tag which is already existing in an array.

tgname = request.form['tags']
x = request.form['newres']

with open('intents.json', 'r') as file:
    data = json.load(file)

for t in data["intents"]:
    if t['tag'] == tgname:

        temp1 = data['responses']
        temp1.append(x)

        with open(filename,'w') as f:
            json.dump(data, f)

I am getting keyword error:'responses'. How to resolve this?

Upvotes: 0

Views: 220

Answers (1)

Raz Kissos
Raz Kissos

Reputation: 295

The data variable contains the entire json object and therefor does not have access to responses, only to intents. Instead you should use the t variable inside your for loop since it iterates across each json object inside the intents list.

for t in data["intents"]:
    if t['tag'] == tgname:

        # Correct:
        temp1 = t['responses']
        temp1.append(x)

        with open(filename,'w') as f: 
            json.dump(data, f)

Upvotes: 1

Related Questions