How to add item to json list - python

From this

data = json.loads(urlopen('someurl').read()) 

I will get:

 {'list': [{'a':'1'}]} 

I want to add {'b':'2'} to the list .

Any idea how to do this?

+7
json python
source share
2 answers

I would do this:

 data["list"].append({'b':'2'}) 

so you just add the object to the list that is present in the "data"

+9
source share

Items are added to the list using append() :

 >>> data = {'list': [{'a':'1'}]} >>> data['list'].append({'b':'2'}) >>> data {'list': [{'a': '1'}, {'b': '2'}]} 

If you want to add an element to a specific place in the list (for example, to the beginning), use insert() instead:

 >>> data['list'].insert(0, {'b':'2'}) >>> data {'list': [{'b': '2'}, {'a': '1'}]} 

After that, you can again compile JSON from the dictionary you changed:

 >>> json.dumps(data) '{"list": [{"b": "2"}, {"a": "1"}]}' 
+5
source share

All Articles