Encoding and decoding with the JSON package

We use the json module for working with JSON in Python. The json package allows you to transform a Python object into a character string that represents those objects in JSON format. Let's create a json representation of a Python list by using the following commands:

>>> import json
>>> books = ['book1', 'book2', 'book3']
>>> json.dumps(books)
'["book1", "book2", "book3"]'

The json.dumps() function allows you to transform a dictionary-type object as the first parameter into a text string in JSON format. In this case, we can see the JSON string appears to be identical to Python's own representation of a list, but note that this is a string. You can confirm this by executing the following commands:

>>> string_books = json.dumps(['book1', 'book2', 'book3'])
>>> type(string_books)
<class 'str'>

The json.loads() function transforms a character string that contains information in JSON format and transforms it into a dictionary Python-type object. Typically, we will receive a JSON string as the body of an HTTP response, which can simply be decoded using json.loads() to provide immediately usable Python objects:

>>> books = '["book1", "book2", "book3"]'
>>> list = json.loads(books)
>>> list
['book1', 'book2', 'book3']
>>> list[1]
'book2'

We can also use the load method to extract the Python object whose representation in JSON format is in the books.json file. In the output, we can see that the type returned is a dictionary when reading a JSON file.

You can find the following code in the read_books_json.py file:

import json
with open("books.json", "rt") as file:
books = json.load(file)

print(books)

print(type(books))

The following is the output for the execution of the previous script:

{'title': 'Learning Python 3', 'author': 'author', 'publisher': 'Packt Publishing', 'pageCount': 500, 'numberOfChapters': 12, 'chapters': [{'chapterNumber': 1, 'chapterTitle': 'Python Fundamentals', 'pageCount': 30}, {'chapterNumber': 2, 'chapterTitle': 'Chapter 2', 'pageCount': 25}]}
<class 'dict'>
..................Content has been hidden....................

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