Skip to main content

Section 15.5 What is JSON?

JSON stands for JavaScript Object Notation. It is a format for sharing data. You can read a JSON string from a file or from a URL and convert it into a Python dictionary or list. You can also convert a Python dictionary or list into a JSON string.

Subsection 15.5.1 Converting a JSON String into a Python Object

In the following program, we use the built-in json library to parse the JSON string and return a Python list of dictionaries.

Checkpoint 15.5.1.

What do you think this code will print? Run it to see what it actually prints.

Checkpoint 15.5.2.

csp-10-2-2: Which method of the json library is used to convert a JSON string into a Python object?
Here is another example. Run the code to see what it does.

Checkpoint 15.5.3.

What do you think this code will print? Run it to see what it actually prints.

Checkpoint 15.5.4.

csp-10-2-4: What type of thing (class name) is data in the code above?

Checkpoint 15.5.5.

csp-10-2-5: What type of thing (class name) is d1 in the code above?

Checkpoint 15.5.6.

    csp-10-2-6: Once you convert a JSON string to Python what are the two possible types for the Python object?
  • dictionary and string
  • Dictionaries are used in JSON, but strings only contain one element, so they are not as useful.
  • dictionary and list
  • JSON is constructed by nesting dictionaries and lists as needed.
  • string and list
  • Lists are used in JSON, but strings only contain one element, so they are not as useful.

Subsection 15.5.2 Converting a Python object into a JSON string

You can also convert a Python list or dictionary to a JSON string.

Checkpoint 15.5.7.

What do you think this code will print? Run it to see what it actually prints.

Checkpoint 15.5.8.

csp-10-2-8: Which method of the json library is used to convert a Python object to a JSON string?