Python JSON Encoder and Decoder
In this tutorial, we will learn Python JSON Encoder and Decoder.
JSON stands for JavaScript Object Notation, it is basically used for storing information easily in an organized manner. It is generally used between a web application and a server. JSON is so easy to understand that a human as well as a machine can read this. It is very lightweight and highly inspired from JavaScript. JSON data formats are very similar to the Python dictionary.
To encode or decode JSON packets to Python objects we need to import the json package, it is a built package in Python. So you need not to install it. These are the following functions that are available in the json module:
Function | Working |
---|---|
dump() | It is used to write encoded json string on file |
dumps() | It is used to convert python objects into JSON format |
load() | It is used to decode the JSON file while reading |
loads() | It is used to convert the JSON string |
Encoding into JSON from Python
We can encode Python objects to JSON format using dumps() function.
Here is the mapping table for JSON to Python and vice versa.
JSON | Python |
---|---|
object | dict (dictionary) |
number(int/long) | int |
number(float) | float |
unicode/string | str (string) |
list, tuple | array |
null | Null |
true | True |
false | False |
Now let us take an example to understand the concept:
#impoting json module import json test = { "name": "Sourav", "age": 20, "student": True, "roll no": 45, "subjects": ("Python","Java"), "pets": ['birds'], "result": [ {"subject": "AI", "passed": 87}, {"subject": "DS & Algo", "passed": 92} ] } #sorting the result in ascending order by keys: sorted_str = json.dumps(test, sort_keys=True) print(sorted_str) #printing the data type print(type(sorted_str))
Output :
{"age": 20, "name": "Sourav", "pets": ["birds"], "result": [{"passed": 87, "subject": "AI"}, {"passed": 92, "subject": "DS & Algo"}], "roll no": 45, "student": true, "subjects": ["Python", "Java"]} <class 'str'>
As you can see the output of the above code will be of a JSON string type.
Let’s create a JSON file of the dictionary and save it to the Hard Disk
#impoting json module import json test = { "name": "Sourav", "age": 20, "student": True, "roll no": 45, "subjects": ("Python","Java") } #we are creating a new test_json.json file with the write mode using file i/o operation with open('test_json.json', "w") as file_write: #writing json data into the file json.dump(test, file_write)
Output:
Nothing will show in the output but a json file with the name test_json.json will be created and saved to the Hard Drive. You can search this file by the file name or you can go to the run menu (start+R) in Windows and enter the file name to view the file.
Compact Encoding of JSON in Python
If we want to reduce the size of the JSON file, we can use compact encoding in Python.
Let’s take an example to understand the concept better:
import json #creating a list that contains dictionary lst = ['x', 'y', 'z',{'6': 7, '8': 9}] #separator is used for compact representation of JSON. #',' is used to identify list items #':' is used to identify key and value in dictionary compact_json = json.dumps(lst, separators=(',', ':')) print(compact_json)
Output :
["x","y","z",{"6":7,"8":9}]
Formatting JSON Code (Pretty Print) in Python
If we want to print JSON string in a well format for human understanding we can do this easily with the help of pretty printing. It takes care of the indent of the code so that we can read it easily.
Let’s take an example to understand the concept:
#impoting json module import json test = { "name": "Sourav", "age": 20, "student": True, "roll no": 45, "subjects": ("Python","Java") } #sorting the result in ascending order by keys: #using indent parameter to change the format of the code sorted_str = json.dumps(test, indent = 5,sort_keys=True) print(sorted_str)
Output :
{ "age": 20, "name": "Sourav", "roll no": 45, "student": true, "subjects": [ "Python", "Java" ] }
As you can see the output JSON string is now well formatted.
JSON to Python Decoding
We can decode JSON string back to Python objects with the help of inbuilt method load() and loads() that are present in the json module.
Let us take an example of decoding to understand the concept:
#importing the json module import json #giving a json data string jsn_str = '{"name": "Sourav", "age": 20, "student": true, "roll no": 45, "subjects": ["Python", "Java"]}' #decoding the JSON format into Python dictionary using loads() method decoded_dict = json.loads(jsn_str) #printing the Python dictionary print(decoded_dict) #checking the type of decoded_dict print("Type of decoded_dict", type(decoded_dict))
Output :
{'name': 'Sourav', 'age': 20, 'student': True, 'roll no': 45, 'subjects': ['Python', 'Java']} Type of decoded_dict <class 'dict'>
If we want to decode any json file from the storage we have to use load () method. Let us take an example where we will decode a JSON file from the Hard Disk using file I/O operation.
Note: JSON file must exist on the storage at the specified path.
#importing json module import json #file I/O open function to read the data from the JSON File #giving the path of the json file #r = raw string literal with open(r'C:\Users\sourav\test_json.json') as file_object: #storing file data in an object decode = json.load(file_object) print(decode)
Output: It’ll convert the JSON string into Python dictionary object. In my case it is –
{'name': 'Sourav', 'age': 20, 'student': True, 'roll no': 45, 'subjects': ['Python', 'Java']}
I hope now you are familiar with the concept of how to Encode and Decode JSON string in Python.
Also read:
Leave a Reply