Reputation: 37866
From this..
data = json.loads(urlopen('someurl').read())
...I will get:
{'list': [{'a':'1'}]}
I want to add {'b':'2'}
into the list
.
Any idea how to do it?
Upvotes: 17
Views: 165622
Reputation: 1165
import json
myDict = {'dict': [{'a': 'none', 'b': 'none', 'c': 'none'}]}
test = json.dumps(myDict)
print(test)
{"dict": [{"a": "none", "b": "none", "c": "none"}]}
myDict['dict'].append(({'a': 'aaaa', 'b': 'aaaa', 'c': 'aaaa'}))
test = json.dumps(myDict)
print(test)
{"dict": [{"a": "none", "b": "none", "c": "none"}, {"a": "aaaa", "b": "aaaa", "c": "aaaa"}]}
Upvotes: 2
Reputation: 11504
Elements are added to list using append()
:
>>> data = {'list': [{'a':'1'}]}
>>> data['list'].append({'b':'2'})
>>> data
{'list': [{'a': '1'}, {'b': '2'}]}
If you want to add element to a specific place in a list (i.e. to the beginning), use insert()
instead:
>>> data['list'].insert(0, {'b':'2'})
>>> data
{'list': [{'b': '2'}, {'a': '1'}]}
After doing that, you can assemble JSON again from dictionary you modified:
>>> json.dumps(data)
'{"list": [{"b": "2"}, {"a": "1"}]}'
Upvotes: 9
Reputation: 2263
I would do this:
data["list"].append({'b':'2'})
so simply you are adding an object to the list that is present in "data"
Upvotes: 39