Understanding of dictionary and json in python

Due to my previous reasons, I know that json is a format of data that is a bit similar to a dictionary. From a formal point of view, it is composed of key and values. For example, the data returned by our interface is mostly in json format. Today, I went to Baidu on the Internet, and solved the problem that was bothering me for a while.

1. Dictionary

Its type is dict, which is a structure for storing data. If its key name is a character, it can be enclosed in double quotation marks (single quotation mark), if it is a number, it can be omitted. The same is true for the key value. If it is a character, it can be enclosed in double quotation marks (single quotation mark), if it is a number, it can be omitted. In addition, the key name cannot be repeated. If it is repeated, it will be updated to the following value.

Two, json

Its type is str, which is a one-character format. The format of json must only use double quotation marks as the key or value boundary symbol. Single quotation marks cannot be used, and double quotation marks must be used for "key". Double quotation marks are not required if the value is a number.

to sum up:

1: Data in json format, which exists in the string str format in python and the dictionary is in dict format;

2: The vacancy in json is null, and the null value in the dictionary is None;

3: All the keys in json are strings and must be enclosed in double quotes; if the value is a number, it is not necessary, but if it is also a string, it must also be enclosed in double quotes;

Three, convert the dictionary to json format

Will import json, use the json.dumps() function

import json
#将字典转换成json字符串
dict_data = {'姓名':'jayce','性别':'女', "age": 23, 10:None, None:True}
reslut_json = json.dumps(dict_data)

print(type(reslut_json),reslut_json)

结果:<class 'str'> {"\u59d3\u540d": "jayce", "\u6027\u522b": "\u5973", "age": 23, "10": null, "null": true}

It is confirmed that json is in string format, and the vacancy in json is null.

If there are multiple dictionaries, put them in the list to nest, as follows:

dict_data = [{'姓名':'jayce','性别':'女', "age": 23, 10:None, None:True},{'姓名':'jayce','性别':'女', "age": 23, 10:None, None:True}]
四、将json格式转换成字典

 You will also import json, just use the json.loads() function. Remember to add single quotes to the outermost json data and put the data inside as a string.

#将json字符串转为字典格式
json_data ='{"data":' \
           '{"姓名": "jayce", "性别": "女", "age": 23}}'
result_dict= json.loads(json_data)
print(type(result_dict),result_dict)

Result: <class'dict'> {'data': {'Name':'jayce','Gender':'Female','age': 23}}

Guess you like

Origin blog.csdn.net/qq_25162431/article/details/108511869