CMP6221: Computing For AI Lab Session 6: JSON Data in Python
CMP6221: Computing For AI Lab Session 6: JSON Data in Python
CMP6221: Computing For AI Lab Session 6: JSON Data in Python
1. Objectives
a. Converting Python objects to JSON
b. Reading and writing a JSON Files
Note: Although most of the instructions in this sheet are written for command line interpreter,
you are advised to save your python codes as scripts.
1. Introduction
We can parse the above JSON string using json.loads() method from the json module. The
result is a Python dictionary.
3. Converting Python Objects to JSON
Using json.dumps() we can convert Python Objects to JSON.
Python JSON
dict Object
Python JSON
list Array
tuple Array
str String
int Number
float Number
True true
False false
None null
Below we'll show how you can convert various Python objects to different JSON data types.
The json module also allows us to write JSON data into a JSON file. JSON files are saved
with the .json extension. Let's see how we can do that below. In order to achieve this, we
use Python's open() function with w as the parameter to signify that we want to write the
file.
json.load vs json.loads
json.load is used when loading a file while json.loads(load string) is used when loading a
string.
json.dump vs json.dumps
We use json.dump when we want to dump JSON into a file. json.dumps(dump string) is
used when we need the JSON data as a string for parsing or printing.
7. Implementation Limitations
The process of encoding JSON is called Serialization while the process of decoding
JSON is called deserialization. Some JSON deserializer implementations may set limits
on:
However such limitations are only those relevant to Python data types and the Python
interpreter itself.
8. Exercise
For this exercise, we will keep track of when our friend’s birthdays are, and be able to find
that information based on their name. Create a dictionary (in a JSON file) of names and
birthdays. When you run your program it should ask the user to enter a name, and return
the birthday of that person back to them. The interaction should look something like this: