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 (so to understand, JSON is a string)
- The Json.dumps () function is an encoding of a Python data type list in JSON format (so you can understand that the json.dumps () function converts a dictionary to a string)
- The Json.loads () function converts the JSON format data to a dictionary (as you can understand, the json.loads () function converts a string into a dictionary)
In the JSON encoding and decoding process, the original Python type and JSON type will be converted to each other, the specific conversions against the following:
Python encoding is a JSON type conversion table:
Python |
JSON |
Dict |
Object |
List, tuple |
Array |
Str |
String |
int, float, int-& float-derived Enums |
Number |
True |
True |
False |
False |
None |
Null |
JSON decodes the corresponding table for the Python type conversion:
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:
ImportJson,time#save data to JSON filedefStore (data): With open ('Data.json','W') as FW:#Convert a dictionary to a string #json_str = json.dumps (data) #fw.write (JSON_STR) #the above two sentences are equivalent to the following sentencejson.dump (DATA,FW)#load JSON data from filedefload (): With open ('Data.json','R') as F:data=json.load (f)returnDataif __name__=="__main__": Json_data='{"Login": [{"username": "AA", "Password": "001"},{"username": "BB", "Password": "002"}], "register": [{"username": "CC", "Password": "003"},{"username": "dd", "Password": "004"}]}' #function is to convert JSON formatted data into a dictionarydata =json.loads (Json_data) store (data) data=load ()Print(data)
Summarize:
Used for manipulating files without s, with s for conversion of data types.
Python read-write JSON file (dump, load), and data processing in JSON format (dumps, loads)