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.
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.
What do you think this code will print? Run it to see what it actually prints.
Here is another example. Run the code to see what it does.
What do you think this code will print? Run it to see what it actually prints.
- 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.
csp-10-2-6: Once you convert a JSON string to Python what are the two possible types for the Python object?
15.5.2. Converting a Python object into a JSON string¶
You can also convert a Python list or dictionary to a JSON string.
What do you think this code will print? Run it to see what it actually prints.