Convert String to JSON in Python

Function json.loads() accepts JSON string and converts it to Python dictionary (deserialization). The last letter in load(s) stands for “string”.

If you run this code, you can display individual elements inside a dictionary. Use the type() function to check the type of the object.

John Doe 35
<class 'dict'>

Load vs Loads

json.load() instead of converting a string, uses it as a path to a file and then converts its contents if they are formatted as JSON file.

Create a file called file.json and insert the following text into it:

{
    "fruit": "pear",
    "size": "medium",
    "color": "yellow"
}

Now, it’s time to load it using the function.

This code opens the file with JSON data and assigns it to a dictionary, then the data is printed.

pear medium yellow

If you change the function load() to loads(), Python is going to return an error.

TypeError: the JSON object must be str, bytes or bytearray, not TextIOWrapper