Python Deserialize JSON File to Object

In this Python tutorial we will learn how to read JSON file content and deserialize to a Python object.

First step is import json package in your source file.

import json

For example you have the JSON file that stored the list of contacts as below located on your computer at ’D:\ToriCode\Python\contacts.json’

[
    {
        "firstName": "Doris",
        "lastName": "Castillo",
        "email": "doris@toricode.com"
    },
    {
        "firstName": "Jerry",
        "lastName": "Fernandez",
        "email": "jerry@toricode.com"
    },
    {
        "firstName": "Jessica",
        "lastName": "Schultz",
        "email": "jessica@toricode.com"
    },
    {
        "firstName": "Janice",
        "lastName": "Stone",
        "email": "janice@toricode.com"
    }
]

To read the JSON file content and assign to a Python string object.

with open('D:\ToriCode\Python\contacts.json', 'r') as f:
    json_data = f.read()

Derserialize a string to Python object using json.loads() method.

contact_list = json.loads(json_data)

To observe the result of json.loads() method we print out the type of return object.

print("Object type: ", type(contact_list))

As the JSON file content is a list of contact objects then we can loop the return object to see the result.

for contact in contact_list:
    print(contact)

The complete Python code of this tutorial.

import json

with open('D:\ToriCode\Python\contacts.json', 'r') as f:
    json_data = f.read()

contact_list = json.loads(json_data)

print("Object type: ", type(contact_list))

for contact in contact_list:
    print(contact)

Execute the Python code above you will get the result as below. Python Deserialize JSON File to Object