The Dict (or object) of Python and the conversion of JSON to each other
In the Python language, the conversion between JSON data and dict dictionaries and objects is an essential operation.
Bring your own JSON library in Python. by import json
Importing.
There are 2 methods in the JSON module,
loads()
: Convert JSON data to dict data
dumps()
: Convert dict data to JSON data
load()
: Reads JSON file data and turns it into dict data
dump()
: The JSON file is written after converting dict data into JSON data
Here's a concrete example:
Dict Dictionary to JSON data
import jsondef dict_to_json(): dict = {} dict[‘name‘] = ‘many‘ dict[‘age‘] = 10 dict[‘sex‘] = ‘male‘ print(dict) # 输出:{‘name‘: ‘many‘, ‘age‘: 10, ‘sex‘: ‘male‘} j = json.dumps(dict) print(j) # 输出:{"name": "many", "age": 10, "sex": "male"}if __name__ == ‘__main__‘: dict_to_json()
Object Goto JSON data
Import Jsondef Obj_to_json (): Stu = Student (' 007 ',' 007 ',28,' Male ',' 13000000000 ',' [email protected] ')PrintType (stu)) # <class' Json_test.student.Student ' > stu = stu.__dict__ # Convert object to dict dictionaryPrintType (stu)) # <class' Dict ' >Print (stu) # {' ID ':' 007 ',' Name ':' 007 ',' Age ': ' sex ': ' male ', ' phone ': ' 13000000000 ', ' email ': " [email protected] '} j = Json.dumps (obj=stu) print (j) # {" id ": " 007 ", " name ": " age ": " sex ": " male ", " phone ": " 13000000000 ", " email ": " [email protected] "}if __name__ = = ' __main__ ': Obj_to_json ()
JSON data into Dict dictionary
import jsondef json_to_dict(): j = ‘{"id": "007", "name": "007", "age": 28, "sex": "male", "phone": "13000000000", "email": "[email protected]"}‘ dict = json.loads(s=j) print(dict) # {‘id‘: ‘007‘, ‘name‘: ‘007‘, ‘age‘: 28, ‘sex‘: ‘male‘, ‘phone‘: ‘13000000000‘, ‘email‘: ‘[email protected]‘}if __name__ == ‘__main__‘: json_to_dict()
Convert JSON data to objects
import jsondef json_to_obj (): j = ' ID: ' + stu.id + ' name: ' + stu.name +
' Age: ' + str (stu.age) +
' sex: ' + str (stu.sex) + if __name__ = ' __main__ ': json_to_obj ()
JSON's
load()
And
dump()
Use of methods
Import JSONdef dict_to_json_write_file(): Dict = {} dict[' name '] = ' many ' dict[' age '] = 1 0 dict[' sex '] = ' Male ' Print (dict) # {' Name ': ' Many ', ' age ': ten, ' sex ': ' Male '} with open (' 1.json ') , ' W ') as f:json.dump (Dict, F) # will generate a 1.json file in the directory, the file content is dict data into the JSON data if __name__ = = ' __main __ ': Dict_to_json_write_file ()
load()
The use
import jsondef json_file_to_dict(): with open(‘1.json‘, ‘r‘) as f: dict = json.load(fp=f) print(dict) # {‘name‘: ‘many‘, ‘age‘: 10, ‘sex‘: ‘male‘}if __name__ == ‘__main__‘: json_file_to_dict()
The Dict (or object) of Python and the conversion of JSON to each other