Using dict with JSON

JSON natively supports a mapping-type object, which is equivalent to a Python dictionary. This means that we can work directly with dict through JSON. In this example, we import the json package and we display the contents of the dictionary-type object called books in JSON format:

>>> import json
>>> books = {'A':'Book1', 'B':'Book2', 'C':'Book3'}
>>> type(books)
<class 'dict'>
>>> books['A']
'Book1'
>>> books['B']
'Book2'
>>> books['C']
'Book3'
>>> books['D']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'D'
>>> json.dumps(books)
'{"A": "Book1", "B": "Book2", "C": "Book3"}'
Now the text string resulting from the conversion will be linked to the name books_json.
>>> books_json = json.dumps(books)
>>> print(books_json)
{"A": "Book1", "B": "Book2", "C": "Book3"}
The string with the representation of an object in JSON format will be transformed to a Python object.
>>> json.loads(books_json)
{'A': 'Book1', 'B': 'Book2', 'C': 'Book3'}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset