- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
JSON Formatting in Python
The JSON (Java Script Object Notation) is light weight, well 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 functionalities, we need to use the json module of Python. The json module comes with the Python standard library. So at first we have to import it first.
import json
Converting Python objects to JSON String
In the json module, there are some methods like dump(), and dumps() to convert Python objects to JSON strings. The dump() method takes two arguments, the first one is the object, and second one is file object. This method serialize the object as JSON formatted stream to file objects. Similarly the dumps() method takes only one argument. The argument is object. It converts the objects to JSON string.
Example code
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
StringIO Object value: ["India", "Australia", "Brazil"] { "name": "Kalyan", "age": 25, "city": "Delhi" }
Converting JSON Strings to Python Objects
In this case we are De-serializing the JSON strings. There are two different methods. These are load() and loads(). Both of these methods takes the JSON file as argument. load() converts to python objects from file objects data, and loads() converts from string type data.
Example code
import json from io import StringIO str_io_obj = StringIO('["xyz", "abc", "xyz", "pqr"]') #load from StringIO print('Load: ' + str(json.load(str_io_obj))) print('String to Json: ' + str(json.loads('{"xyz" : 1, "abc" : 2, "xyz" : 3, "pqr" : 4}')))
Output
Load: ['xyz', 'abc', 'xyz', 'pqr'] String to Json: {'xyz': 3, 'abc': 2, 'pqr': 4}
JSON Encoder and Decoder Classes in Python
The JSONEncoder class is used to convert Python Objects to JSON format. Here in this example we will see how a complex number object can be converted as JSON type object using the JSONEncoder.
Example code
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
[5.0, 8.0]
The JSONDecoder class performs the reverse action.
Example code
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
{'Asim': '28', 'Priyesh': 23} ({'Asim': '28', 'Priyesh': 23}, 44)