Json is a lightweight data interchange format. The so-called json is a data format: in Python it is actually a dictionary.
The json module has only 4 methods in total:
dumps, dumps, encodes Python objects into JSON strings
loads, load decode the encoded JSON string into a Python object
where dump and load must pass in a file handle. dumps are only done serializing to str.
Serialize to a string: Change all the original single quotes to double quotes. Then add a layer of single quotes outside
import json dic1={'name':'zs','age':18} dic2 = json.dumps(dic1) print (dic2) # {"name": "zs", "age": 18} turned out to be single quotes print (json.loads(dic2)) # {'name': 'zs' , 'age': 18}
# json.dump() usage: the first step is to serialize it into a string, and the second step is to write it into the file import json j={'name':'zs','age':33} with open('test_json2','w')as f: json.dump(j,f,indent=4)
# Usage of json.load(): import json with open('test_json2','r')as f: print(json.load(f)) #{'name': 'zs', 'age': 33}