Python Read/Write JSON
1. json.dumps
convert dictionary
to string
in Python
import json
test_dict = {
'info': [
{"id": "11111"},
{
1: [['iPhone', 6300],
['Bike', 800],
['shirt', 300]]
}
]
}
print(test_dict)
print(type(test_dict))
#dumps dict --> str
json_str = json.dumps(test_dict)
print(json_str)
print(type(json_str))
2. json.loads
convert string
to dictionary
in Python
new_dict = json.loads(json_str)
print(new_dict)
print(type(new_dict))
3. json.dump
write the dict
into a JSON
file
with open("test.json","w") as f:
json.dump(new_dict,f)
print("file write successfully...")
4. json.load
read the JSON
file
with open("test.json",'r') as load_f:
load_dict = json.load(load_f)
print("file read successfully...")
print(load_dict)
5. Complete Code
import json
test_dict = {
'info': [
{"id": "11111"},
{
1: [['iPhone', 6300],
['Bike', 800],
['shirt', 300]]
}
]
}
print(test_dict)
print(type(test_dict))
#dumps dict --> str
json_str = json.dumps(test_dict)
print(json_str)
print(type(json_str))
new_dict = json.loads(json_str)
print(new_dict)
print(type(new_dict))
with open("test.json","w") as f:
json.dump(new_dict,f)
print("file write successfully...")
with open("test.json",'r') as load_f:
load_dict = json.load(load_f)
print("file read successfully...")
print(load_dict)