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?
There are two methods to add elements to the list. add(E e ) : appends the element at the end of the list. Since List supports Generics , the type of elements that can be added is determined when the list is created. add(int index , E element ) : inserts the element at the given index .
Elements can be added in the list using built-in functions like append(), insert(). append() adds the elements at the end of the list, while insert() adds the element at the specified position. extend() function and + operator is used to concatenate elements from one list/tuple into the other.
Python provides a method called .append() that you can use to add items to the end of a given list.
append() and . extend() methods to add elements to a list. You can add elements to a list using the append method. The append() method adds a single element towards the end of a list.
I would do this:
data["list"].append({'b':'2'})
so simply you are adding an object to the list that is present in "data"
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"}]}'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With