1.

What is JSON? How can Python objects be represented in JSON format?

Answer»

The acronym JSON stands for JavaScript Object Notation based on a subset of the JavaScript language. It is a lightweight data interchange format which is easy for humans to use and easy for machines to parse.

Python library provides json MODULE for converting Python objects to JSON format and VICE versa. It contains dumps() and loads() FUNCTIONS to serialize and de-serialize Python objects.

>>> import json >>> #dumps() converts Python object to JSON >>> data={'name':'Raju', 'subjects':['phy', 'che', 'maths'], 'marks':[50,60,70]}    >>> jso=json.dumps(data) >>> #loads() converts JSON string back to Python object >>> Pydata=json.loads(jso) >>> Pydata {'name': 'Raju', 'subjects': ['phy', 'che', 'maths'], 'marks': [50, 60, 70]}

The json module has dump() and load() functions that perform serialization and deserialization of Python object to a File like object such as disk file or network stream. In the following example, we store JSON string to a file using load() and retrieve Python dictionary object from it. Note that File object must have relevant ‘write’ and ‘read’ permission.

>>> data={'name':'Raju', 'subjects':['phy', 'che', 'maths'], 'marks':[50,60,70]}    >>> file=open('testjson.txt','w') >>> json.dump(data, file)    >>> file.close()

The ‘testjson.txt’ file will SHOW following contents:

{"name": "Raju", "subjects": ["phy", "che", "maths"], "marks": [50, 60, 70]}

To load the json string from file to Python dictionary we use load() function with file opened in ‘R’ mode.

>>> file=open('testjson.txt','r') >>> data=json.load(file) >>> data {'name': 'Raju', 'subjects': ['phy', 'che', 'maths'], 'marks': [50, 60, 70]} >>> file.close()

The json module also provides object oriented API for the purpose with the help of JSONEncode and JSONDecoder classes.

The module also defines the relation between Python object and JSON data type for interconversion, as in the following table:

Python
JSON
dict
object
list, tuple
Array
str
String
int, float, int- & float-derived Enums
Number
True
True
False
False
None
Null


Discussion

No Comment Found