Reputation: 309
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
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
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