1, Json.dumps ()
Json.dumps () is used to convert data of type dict to STR, because if an error is written directly to the dict type of data to the JSON file, the function needs to be used when writing the data.
ImportJsonname= {'a':'Zhangsan','b':'Lisi','C':'Mawu','D':'Zhaoliu'}jsdumps=json.dumps (name)Print(Name,'type is:%s'%type (name))Print(Jsdumps,'type is:%s'%type (Jsdumps))
Result is
{'a':'Zhangsan','b':'Lisi','C':'Mawu','D':'Zhaoliu'} type is:<class 'Dict'>{"a":"Zhangsan","b":"Lisi","C":"Mawu","D":"Zhaoliu"} type is:<class 'Str'>
2, Json.dump ()
Json.dump () is used to convert data of type dict to STR and write to a JSON file. There are two ways to write data to a JSON file
Importjsonnamelist= {'a':'Zhangsan','b':'Lisi','C':'Mawu','D':'Zhaoliu'}filename= ('./namejson.json')#Method 1 #现将字典转为字符串, in the Write fileJsobj =Json.dumps (NameList) with open (FileName,"W", encoding= ' Utf-8 ') as F:
F.write (Jsobj)
F.close ()
#Method 2 # Write directly to the file in format: json.dump (dictionary or list, open file, ensure_ascii=false) turn off ASCII transcoding
Json.dump (NameList, open (FileName, "w", encoding= ' Utf-8 '), Ensure_ascii=false)
3, Json.loads ()
Json.loads () is used to convert data of type STR to Dict.
ImportJsonname= {'a':'Zhangsan','b':'Lisi','C':'Mawu','D':'Zhaoliu'}jsdumps=json.dumps (name) jsloads=json.loads (jsdumps)Print(Name,'type is:%s'%type (name))Print(Jsdumps,'type is:%s'%type (jsdumps))Print(Jsloads,'type is:%s'%type (jsloads))
Result is
{'a':'Zhangsan','b':'Lisi','C':'Mawu','D':'Zhaoliu'} type is:<class 'Dict'>{"a":"Zhangsan","b":"Lisi","C":"Mawu","D":"Zhaoliu"} type is:<class 'Str'>{'a':'Zhangsan','b':'Lisi','C':'Mawu','D':'Zhaoliu'} type is:<class 'Dict'>
4, Json.load ()
Json.load () is used to read data from a JSON file.
Import= ('./emb_json.json'= json.load (open (Emb_filename)) Print(jsobj)print(type (jsobj)) for in Jsobj.keys (): print('key:%s value:%s' % (key, Jsobj.get (key)))
Result is
{'a':'Zhangsan','b':'Lisi','C':'Mawu','D':'Zhaoliu'}<class 'Dict'>key:a value:zhangsankey:b value:lisikey:c value:mawukey:d Value:zhaoliu
Description of dumps, loads, dump, and load functions in the Python JSON module