English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
JSON (JavaScript Object Notation) is a lightweight, widely accepted data interchange format. Using JSON formatting techniques in Python, we can convert JSON strings to Python objects, and also convert Python objects to JSON strings.
To use these features, we need to use Python's json module. The json module is attached to the Python standard library. Therefore, we must first import it.
import json
In the json module, there are some methods, such as dump() and dumps(), which can convert Python objects to JSON strings. The dump() method has two parameters, the first is the object, and the second is the file object. This method converts the object to a JSON formatstreamserialize to file object. Similarly, the dumps() method only accepts one parameter. The parameter is the object. It converts the object to JSONString.
import json from io import StringIO str_io_obj = StringIO() #Use JSON Dump to make StringIO json.dump(["India", "Australia", "Brazil"], str_io_obj) print('StringIO Object value: ') + str(str_io_obj.getvalue()) my_json = { "name" : "Kalyan", "age" : 25, "city" : "Delhi" } print(json.dumps(my_json, indent=4))
Output result
StringIO Object value: ["India", "Australia", "Brazil"] { "name": "Kalyan", "age": 25, "city": "Delhi" }
In this case, we will deserialize the JSON string. There are two different methods. They are load() and load(). Both methods take a JSON file as a parameter. load() converts file object data to a python object, while load() converts string type data to .
import json from io import StringIO str_io_obj = StringIO('["xyz", "abc", "xyz", "pqr"]') str_io_obj = StringIO('["xyz", "abc", "xyz", "pqr"]') #load from StringIO + print('Load: ' str(json.load(str_io_obj)) + print('String to Json: ' 1str(json.loads('{"xyz": 2, 'abc': 3, 'xyz': 4, 'pqr':
Output result
Load: ['xyz', 'abc', 'xyz', 'pqr']} String to Json: {'xyz': 3, 'abc': 2, 'pqr': 4}
The JSONEncoder class is used to convert Python objects to JSON format. In this example, we will see how to use JSONEncoder to convert complex object to JSON type object.
import json class Comp_Encoder(json.JSONEncoder): def default(self, comp_obj): if isinstance(comp_obj, complex): return [comp_obj.real, comp_obj.imag] return json.JSONEncoder.default(self, comp_obj) print(json.dumps(5+8j, cls=Comp_Encoder)
Output result
[5.0, 8.0]
The JSONDecoder class performs the opposite operation.
import json my_str = '{"Asim" : 25, 'Priyesh' : 23, 'Asim' : "28"} #Decode JSON using the JSONDecoder print(json.JSONDecoder().decode(my_str)) print(json.JSONDecoder().raw_decode(my_str))
Output result
{'Asim': ''}28', 'Priyesh': 23} ({'Asim': ''}28', 'Priyesh': 23}, 44)