Learnmonkey Learnmonkey Logo
× Warning:

The tutorial you are reading is currently a work in-progress.

Python JSON

What is JSON?

JSON is an easily understandable way to store data. It is basically like a giant Python dictionary, but in an easily changeable and extensible file. JSON files end in .json.

The json module

Python has a built-in module called json which makes it easy to use JSON in our applications and scripts.

Converting JSON to Python

To convert JSON text to a Python dictionary, we can use the loads() function in the json module:


import json
x = """
{
    "name": "Learnmonkey",
    "year_created": 2022
}
"""
y = json.loads(x)
print(y)
    

The code returns:

{'name': 'Learnmonkey', 'year_created': 2022}

Converting Python to JSON

To convert JSON text into a Python object, we use the dumps() function in the json module:


import json
x = {
    "name": "Learnmonkey",
    "year_created": 2022
}
y = json.dumps(x)
print(y)
    

The code returns:

{"name": "Learnmonkey", "year_created": 2022}