SON (JavaScript Object Notation) Is a lightweight data exchange format .Python3 Can be used in json Module to JSON Data encoding and decoding , It mainly includes the following 4 An operation function :
Tips : The so-called class file objects refer to those with read() perhaps write() Object of method , for example ,f = open('a.txt','r'), Among them f Yes read() Method , therefore f It's a class file object .
stay json In the process of encoding and decoding ,python The original type of JSON The types will switch to each other , The specific transformation contrast is as follows :
Python Encoded as JSON Type conversion correspondence table :
JSON Decoding for Python Type conversion correspondence table :
The operation sample :
import json data = { 'name': 'pengjunlee', 'age': 32, 'vip': True, 'address': {'province': 'GuangDong', 'city': 'ShenZhen'} } # take Python Dictionary type to JSON object json_str = json.dumps(data) print(json_str) # result {"name": "pengjunlee", "age": 32, "vip": true, "address": {"province": "GuangDong", "city": "ShenZhen"}} # take JSON Object type is converted to Python Dictionaries user_dic = json.loads(json_str) print(user_dic['address']) # result {'province': 'GuangDong', 'city': 'ShenZhen'} # take Python The dictionary is output directly to a file with open('pengjunlee.json', 'w', encoding='utf-8') as f: json.dump(user_dic, f, ensure_ascii=False, indent=4) # In the class file object JSON The string is converted directly to Python Dictionaries with open('pengjunlee.json', 'r', encoding='utf-8') as f: ret_dic = json.load(f) print(type(ret_dic)) # result <class 'dict'> print(ret_dic['name']) # result pengjunlee
Be careful : Use eval() Can implement simple string and Python Conversion of types .
user1 =eval('{"name":"pengjunlee"}') print(user1['name']) # result pengjunlee