Function json.loads() accepts JSON string and converts it to Python dictionary (deserialization). The last letter in load(s) stands for “string”.
1 2 3 4 5 6 7 8 |
import json my_string = '{"first_name": "John", "last_name": "Doe", "age": 35}' my_dict = json.loads(my_string) print(my_dict['first_name'], my_dict['last_name'], my_dict['age']) print(type(my_dict)) |
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.
1 2 3 4 5 6 |
import json with open("D://file.json", "r") as content: my_dict = json.load(content) print(my_dict['fruit'], my_dict['size'], my_dict['color']) |
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