1. JSON string is
2, need to be introduced in advance, that is, import
3. Convert list/dictionary to JSON data type: Json.dumps ()
#json. Dumps (d) #把list \ Dictionary to JSON
#json. Dumps (d,indent=8) #把list \ Dictionary into JSON, indent indent
#json. Dumps (d,indent=8,ensure_ascii=false) #可以显示这中文
Import JSON
d={' car ': {' color ': ' Red ', ' price ': ' + ', ' count ': 30},
' phone ': {' color ': ' Red ', ' price ': ' + ', ' count ': 30},
' pen ': {' color ': ' Red ', ' price ': ' + ', ' count ': 30},
' Flower ': {' color ': ' Red ', ' price ': ' + ', ' count ': 30},
' phone ': {' color ': ' Yel ', ' price ': ' + ', ' count ': 30}
}
#res =json.dumps (d) #把list \ Dictionary to JSON
#res =json.dumps (d,indent=8) #把list \ Dictionary into JSON, indent indent
Res=json.dumps (d,indent=8,ensure_ascii=false) #可以显示这中文
Print (RES)
Print (Type (res))
4. JSON data type Python type (dictionary or list): Json.loads ()
JSON data string must be double quotation marks, cannot be single quotation marks, otherwise the program error
F1=open (' F1 ', ' r ', encoding= ' utf-8 ')
Res=f1.read ()
Dict_res=json.loads (RES) #将json串 converted to a dictionary or list, based on the format of the JSON string
Print (Dict_res)
Print (Type (dict_res))
5, JSON automatic and file operation:
Json.dump (d,f1,ensure_ascii=false,indent=4) #dump operation file, the information is automatically written to the file, the first parameter is data, the second is a file object
#例如
#f1 =open (' F1 ', ' W ', encoding= ' utf-8 ')
# json.dump (d,f1,ensure_ascii=false,indent=4) #dump operation file, the information is automatically written to the file, the first parameter is data, the second is a file object
# json.load ()
Json.load (F1) #直接传入文件对象, will automatically read
#例如
F1=open (' F1 ', encoding= ' utf-8 ')
Print (Json.load (F1))
6.
7.
Python-json processing