Json.dumps () extension referred to in the previous article (Python3+requests:get/post request)
1.json.dumps () to convert data of type dict to Str
Note: The file path is preceded by R to avoid escaping
1 ImportJSON2 3Dict = {'a':'wo','b':'Zai','C':'Zhe','D':'Li'}4String =json.dumps (dict)5 Print(dict)6 Print(String)7 Print(Type (dict))8 Print(Type (string))9 TenWith open (r'C:\Users\zy\Documents\GitHub\python3\searchTest\json.json','W') as F: OneF.write (String)
1{'a':'wo','b':'Zai','C':'Zhe','D':'Li'}2{"a":"wo","b":"Zai","C":"Zhe","D":"Li"}3<class 'Dict'>4<class 'Str'>
If no conversion is performed, an error is made: Typeerror:write () argument must be str, not dict
1 ImportJSON2 3Dict = {'a':'wo','b':'Zai','C':'Zhe','D':'Li'}4With open (r'C:\Users\zy\Documents\GitHub\python3\searchTest\json.json','W') as F:5F.write (Dict)
1{'a':'wo','b':'Zai','C':'Zhe','D':'Li'}2 Traceback (most recent):3<class 'Dict'>4File"c:/users/zy/documents/github/python3/searchtest/json_test.py", line 11,inch<module>5 f.write (dict)6Typeerror:write () argument must be str, notDict
2.json.loads (): Used to convert data of type STR to Dict
1Dict = {'a':'wo','b':'Zai','C':'Zhe','D':'Li'}2dumps =json.dumps (dict)3Loads =json.loads (dumps)4 5 Print(dict)6 Print(dumps)7 Print(loads)8 9 Print(Type (dict))Ten Print(Type (dumps)) One Print(Type (loads))
1{'a':'wo','b':'Zai','C':'Zhe','D':'Li'}2{"a":"wo","b":"Zai","C":"Zhe","D":"Li"}3{'a':'wo','b':'Zai','C':'Zhe','D':'Li'}4<class 'Dict'>5<class 'Str'>6<class 'Dict'>
3.json.dump () to convert data of type dict to STR and write to JSON file
1Dict = {'a':'wo','b':'Zai','C':'Zhe','D':'Li'}2Json.dump (Dict,open (R'C:\Users\zy\Documents\GitHub\python3\searchTest\json.json','W'))
4.json.load () to read data from a JSON file
1 filename = (r'C:\Users\zy\Documents\GitHub\python3\searchTest\json.json' )2 jsobj = json.load (open (filename))3print(jsobj)4 Print(Type (jsobj))
1{'a':'wo','b':'Zai','C':'Zhe','D':'Li'}2<class 'Dict'>
Python:json module dumps, loads, dump, load introduction