JSON (JavaScript Object Notation) is a lightweight data interchange format. It is based on a subset of ECMAScript.
1. json.dumps() and json.loads() are json format processing functions (it can be understood that json is a string)
- The json.dumps() function encodes a list of Python data types in json format (it can be understood that the json.dumps() function converts a dictionary into a string)
- The json.loads() function converts json format data into a dictionary (it can be understood that the json.loads() function converts a string into a dictionary)
During the encoding and decoding process of json, the original type of python and the json type will be converted to each other. The specific conversion comparison is as follows:
Python encoding to JSON type conversion correspondence table:
Python | JSON |
---|---|
dict | object |
list, tuple | array |
str | string |
int, float, int- & float-derived Enums | number |
True | true |
False | false |
None | null |
JSON decoding to Python type conversion correspondence table:
JSON | Python |
---|---|
object | dict |
array | list |
string | str |
number (int) | int |
number (real) | float |
true | True |
false | False |
null | None |
2. json.dump() and json.load() are mainly used to read and write json file functions
Examples are as follows:
import json,time # save data to json file def store(data): with open( ' data.json ' , ' w ' ) as fw: #Convert the dictionary to a string # json_str = json.dumps(data) # fw.write(json_str) #The above two sentences are equivalent to the following json. dump(data,fw) # load json data from file def load(): with open('data.json','r') as f: data = json.load(f) return data if __name__ == "__main__": json_data = '{"login":[{"username":"aa","password":"001"},{"username":"bb","password":"002"}],"register":[{"username":"cc","password":"003"},{"username":"dd","password":"004"}]}' # 函数是将json格式数据转换为字典 data = json.loads(json_data) store(data) data = load() print(data)
Summarize:
The one without s is used to manipulate files, and the one with s is used for data type conversion.