Python JSON Encoder and Decoder Methods

What is json ?

  • JSON (JavaScript Object Notation) is a lightweight data-interchange format.
  • It is easy for machines to parse and generate.
  • It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999.
  • JSON is a text format that is completely language independent.

JSON encoder and decoder

Python provides the predefined methods for JSON encoder and decoder.

Translations from JSON format to python object

JSON Python
object dict
array list
string str
number (int) int
number (real) float
true True
false False
null None

Translations from python object to JSON format

Python JSON
dict object
list, tuple array
str string
int, float, int & float derived enums number
True true
False false
None null

Convert Python Object into JSON Format

json.dumps method is used to encode python object into json format data.
#!/usr/bin/python                                                               
                                                                                
import json                                                                     
                                                                                
print(json.dumps(['json1', {'json2': ('json3', None, 1.0, 2)}]))  
Output:
$ python test_json.py 
["json1", {"json2": ["json3", null, 1.0, 2]}]
#!/usr/bin/python                                                               
                                                                                
import json                                                                     
                                                                                
print(json.dumps("\"json1\njson2"))  
Output:
$ python test_json.py 
"\"json1\njson2"

JSON Encoding with Sorting Order

#!/usr/bin/python                                                               
                                                                                
import json                                                                     
                                                                                
print(json.dumps({"d": 1, "b": 2, "f": 3}, sort_keys=True))   
Output:
$ python test_json.py 
{"b": 2, "d": 1, "f": 3}

Compact JSON encoding in python

#!/usr/bin/python                                                               
                                                                                
import json                                                                     
                                                                                
print(json.dumps([1, 2, 3, {'4': 5, '6': 7}], separators=(',', ':')));   
Output:
$ python test_json.py 
[1,2,3,{"4":5,"6":7}]

Encoding JSON format data with required printing indents

#!/usr/bin/python                                                               
                                                                                
import json                                                                     
                                                                                
print(json.dumps({'d': 2, 'c': 3}, sort_keys=True, indent=4))  
Output:
$ python test_json.py 
{
    "c": 3, 
    "d": 2
}

Python Object Serialization

json.dump() method is used to serialize the object to a file as JSON format.
#!/usr/bin/python                                                               
                                                                                
import json                                                                     
                                                                                
json_data = [1, 'json', 'list'];                                                
                                                                                
f = open("file_name.txt", "w");                                                 
json.dump(json_data, f);                                                        
f.close();                                                                      
print("serialized python object into JSON Format");  
Output:
$ python test_json.py 
serialized python object into JSON Format

file_name.txt file contains below text
[1, "json", "list"] 

Convert JSON Format into Python Object

json.loads method is used to convert JSON format data into python object.
#!/usr/bin/python                                                               
                                                                                
import json                                                                     
                                                                                
print(json.loads('["json1", {"json2":["json3", null, 1.0, 2]}]'));   
Output:
$ python test_json.py 
[u'json1', {u'json2': [u'json3', None, 1.0, 2]}]
#!/usr/bin/python                                                               
                                                                                
import json                                                                     
                                                                                
print(json.loads('"\\"json1\\njson2"'));  
Output:
$ python test_json.py 
"json1
json2

Custom JSON Format Decoding in python

#!/usr/bin/python                                                               
                                                                                
import json                                                                     
                                                                                
def need_sum(dict):                                                             
    if '__sum__' in dict:                                                       
         return (dict['value1']+dict['value2']);                                
    return dict;                                                                
                                                                                
print(json.loads('{"__sum__": true, "value1": 8, "value2": 5}', object_hook=need_sum));
Output:
$ python test_json.py 
13

Python Object Deserialization

json.load() method is used to decode the json format data in a file to python object.
#!/usr/bin/python                                                               
                                                                                
import json                                                                     
                                                                                                                                                                                                                   
f = open("file_name.txt", "r");                                                 
print(json.load(f));                                                            
f.close();         
Output:
$ python test_json.py 
[1, u'json', u'list']

Privacy Policy  |  Copyrightcopyright symbol2020 - All Rights Reserved.  |  Contact us   |  Report website issues in Github   |  Facebook page   |  Google+ page

Email Facebook Google LinkedIn Twitter
^