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 :
to read this, i can use the load function from the json module by passing the file pointer.
Writing to a file :
suppose you have a python list, which you want to write to a json file :
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 :