JSON is the standard data format that be used to save and transfer text data between programs. It is independent from programming language. Python provide built-in json module to process JSON string and Python object conversion. This article will give you some example.
1. JSON String And Python Object Conversion Overview.
Before you can use json module, you should import it first.
import json
1.1 Convert Dict Object To JSON String.
Create a dict object.
Call json.dumps() method to get JSON string from dict object.
import json
# Convert a python dict object to JSON string.
def python_dict_to_json_string():
# Create a dict object.
dict_object = dict(name='Richard', age=25, score=100)
# Call json.dumps method.
json_string = json.dumps(dict_object)
# Print JSON string in console.
print(json_string)
if __name__ == '__main__':
python_dict_to_json_string()
Below is the output.
{"name": "Richard", "age": 25, "score": 100}
1.2 Convert JSON String To Dict Object.
Create a JSON string.
Call json.loads() method to return the python dict object.
import json# Convert JSON string to python dict.defpython_json_string_to_dict():# Create a JSON string. json_string ='{"name": "Tom", "age" : 25, "score" : 100 }'# Load the JSON string to python dict object. dict_object = json.loads(json_string)# Print dict value by key.print(dict_object["name"])print(dict_object["score"])print(dict_object["age"])if__name__=='__main__':python_json_string_to_dict()
Below is the output.
Tom
100
25
2. Dump Python Dict To JSON File Or Load Dict From JSON File.
2.1 Dump Dict To JSON File.
Call open method to get a file object.
Call json.dump(dict_object, file_object) to save dict data to JSON file.
import json# Save a python dict object to JSON format file.defpython_dict_to_json_file(file_path):try:# Get a file object with write permission. file_object =open(file_path, 'w') dict_object =dict(name='Tom', age=25, score=100)# Save dict data into the JSON file. json.dump(dict_object, file_object)print(file_path +" created. ")exceptFileNotFoundError:print(file_path +" not found. ")if__name__=='__main__':python_dict_to_json_file("./teacher_data.json")
When you execute above code, you can find the teacher_data.json file in current execution folder.
2.2 Load JSON File Data To Python Dict.
Create a python file object by open method.
Call json.load method to retrieve the JSON file content to a python dict object.
import json# Load JSON file string to python dict.defpython_json_file_to_dict(file_path):try:# Get a file object with write permission. file_object =open(file_path, 'r')# Load JSON file data to a python dict object. dict_object = json.load(file_object)print(dict_object)exceptFileNotFoundError:print(file_path +" not found. ")if__name__=='__main__':python_json_file_to_dict("./teacher_data.json")
3. Python Class Instance Serialize And Deserialize.
Besides serialize/deserialize Python dict object between JSON string or file. We can also dump / load any Python class instance between JSON string or file.READ : How To Use User Defined Exception In Python
3.1 Dump Python Class Instance To JSON String.
Create a python class.
Add a method which can return a python dict object based on the class instance.
# Convert Teacher class instance to a python dict object. defteacher_to_dict(self,teacher): dict_ret =dict(name=teacher.name, sex=teacher.sex, age=teacher.age)return dict_ret
Call json.dumps(class_instance, default=self.teacher_to_dict) method and set the convert method name in step 2 to parameter default. If do not set the default parameter value, it will throw TypeError: Object of type âTeacherâ is not JSON serializable error.
Add a method which can return a class instance from loaded python dict object.
# Convert a dict object to a Teacher class instance. defdict_to_teacher(self,dict): name = dict['name'] sex = dict['sex'] age = dict['age'] ret =Teacher(name, sex, age)return ret
Call json.loads(json_string, object_hook=self.dict_to_teacher) method and pass the method name in step 2 to the object_hook parameter.
It is similar with steps in 3.1. The difference is you should call json.dump(class_instance, file_object, default=self.teacher_to_dict) method.
3.4 Load JSON File String To Python Class Instance.
It is similar with steps in 3.2. The difference is you should call json.load(file_object, object_hook=self.dict_to_teacher) method.
3.5 Python Class Instance And JSON Conversion Example.
'''Created on Aug 19, 2018@author: zhaosong'''import json# Define a python class.classTeacher(object):# This is the class initialization method.def__init__(self,name,sex,age): self.name = name self.sex = sex self.age = age# Convert Teacher class instance to a python dict object. defteacher_to_dict(self,teacher): dict_ret =dict(name=teacher.name, sex=teacher.sex, age=teacher.age)return dict_ret# Convert a dict object to a Teacher class instance. defdict_to_teacher(self,dict): name = dict['name'] sex = dict['sex'] age = dict['age'] ret =Teacher(name, sex, age)return ret# Translate Teacher object to JSON string. defteacher_object_to_json(self): json_string = json.dumps(self, default=self.teacher_to_dict)print(json_string)return json_string# Translate JSON string to Teacher object.defjson_string_to_teacher_object(self,json_string): teacher_object = json.loads(json_string, object_hook=self.dict_to_teacher)print(teacher_object.name)print(teacher_object.sex)print(teacher_object.age)return teacher_object# This method will save Teacher instance data as a JSON string into a file.defsave_teacher_json_to_file(self,file_path):try: file_object =open(file_path, 'w') json.dump(self, file_object, default=self.teacher_to_dict)print("Teacher object has been saved in file "+ file_path)exceptFileNotFoundError:print(file_path +" not found.")# This method will load a JSON string from file and return a Teacher class instance. defload_teacher_json_from_file(self,file_path):try: file_object =open(file_path) teacher_object = json.load(file_object, object_hook=self.dict_to_teacher)print("name : "+ teacher_object.name)print("sex : "+ teacher_object.sex)print("age : "+str(teacher_object.age))exceptFileNotFoundError:print(file_path +" not found.")if__name__=='__main__':# Convert custom python class instance to JSON string. teacher =Teacher('Jerry', 'Male', 26)print(json.dumps(teacher, default=teacher.teacher_to_dict))# Convert JSON string to custom python class instance. teacher_json_string ='{"name":"Jerry", "sex":"Male", "age":25}' teacher =Teacher('','',1) teacher.json_string_to_teacher_object(teacher_json_string) teacher =Teacher('Tom', 'Male', 25)# Save teacher object to JSON file. teacher.save_teacher_json_to_file('./teacher.json')# Load teach data from JSON file and return a teacher instance. teacher.load_teacher_json_from_file("./teacher.json")