Chris Meek
Chris Meek

Reputation: 309

appending onto JSON in python

I have a JSON file that has peoples names in and lists there children.

people.json:

{
    "person": [
        {
            "Id": 0,
            "firstName": "Bob",
            "lastName": "Bruce",
            "children": [
                {
                    "Id": 0,
                    "Name": "Phil",
                },
                {
                    "Id": 1,
                    "Name": "Dave",
                }
            ]
        },
        {
            "Id": 1,
            "firstName": "Fred",
            "lastName": "Gone",
            "children": [
                {
                    "Id": 0,
                    "Name": "Harry",
                }
            ]
        }
    ]
}

I want to be able to add a child onto a person. How would I go about doing this. This is my attempt to add a child onto Fred.

people.py

import json

json_data = open("people.json")

data = json.load(json_data)

for d in data['person']:
    if d['firstName'] == "Fred":
        d['children'] + [{u'Id': 1, u'Name': u'Rich'}]
        print d['children']

When it prints out it only prints out the existing data and not what I have tried to add

Upvotes: 0

Views: 1766

Answers (2)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798676

This line:

d['children'] + [{u'Id': 1, u'Name': u'Rich'}]

changes nothing.

d['children'].append({u'Id': 1, u'Name': u'Rich'})

Upvotes: 1

sedavidw
sedavidw

Reputation: 11691

Your line:

d['children'] + [{u'Id': 1, u'Name': u'Rich'}]

isn't actually adding it in, just calculating it. You can do

d['children'].append({u'Id': 1, u'Name': u'Rich'})

Upvotes: 2

Related Questions