Python json module

Python json module

the python json module let's you read json data from file, write data to a json file, convert python data structures to a json string, convert json strings to a python native object.

What i'll do in this blog post, reading, writing, converting etc.

Reading a json file :

suppose you have a json file with the following data :

[
    {
        "id": 1,
        "category": "gadgets"
    },
    {
        "id": 2,
        "category": "clothes"
    }
]

to read this, i can use the load function from the json module by passing the file pointer.

import json 

filename = "data.json"

with open(filename, "r") as f:
    data = json.load(f)

print(data)

Writing to a file :

suppose you have a python list, which you want to write to a json file :

[
    {
        "id": 1,
        "category": "gadgets"
    },
    {
        "id": 2,
        "category": "clothes"
    }
]
import json 

data = [
    {
        "id": 1,
        "category": "gadgets"
    },
    {
        "id": 2,
        "category": "clothes"
    }
]

with open("data.json", "w") as f:
    json.dump(data, f)

Converting a python list to a json string :

import json

data = [
    {
        "id": 1,
        "category": "gadgets"
    },
    {
        "id": 2,
        "category": "clothes"
    }
]

json_string = json.dumps(data)
print(f"json_string : {json_string}")

Converting a json string to python native object :

import json

json_string = '[{"id": 1, "category": "gadgets"}, {"id": 2, "category": "clothes"}]'

json_obj = json.loads(json_string)
print(f"json_obj : {json_obj}")