A. JSON into a dictionary:
Product.json file: Converts the contents of the file into a Python dictionary, as follows:
Method one: Use. Loads (), read first and then convert
Import JSON #导入json, note: The JSON string is a string
f = open (' Product.json ', encoding = ' utf-8 ')
res = F.read ()
Product_dic = json.loads (res) #把json串, into Python data type, dictionary
Print (pruduct_dic) #如结果:
Method two: Use. Load (File object), automatically read the file and convert
f = open (' Product.json ', encoding = ' utf-8 ')
Product_dic = Json.load (f) #传一个文件对象, load () is an automatic read and convert file
Print (product_dic) #如结果:
Two. Dictionary converted to JSON string
Method one:. Dumps (dictionary name)
The dictionary is as follows:
FW = open (User_info.json ', ' w ', encoding = ' utf-8 ')
Dic_json = Json.dumps (d,ensure_ascii=false,indent=4) #字典转化成json, the dictionary is converted into a string. Which, D, dictionary; ensure_ascii=false processing Chinese, remove the words will be garbled, Indent=4,json format indent bytes
Fw.write (Dic_json)
The results are as follows:
Method two:. Dump (dictionary name)
FW = open (User_info.json ', ' w ', encoding = ' utf-8 ')
Dic_json = Json.dump (d,fw,ensure_ascii=false,indent=10) #直接操作文件, do not write
View the file results as follows:
Conversion of JSON string to Python type (dictionary)