Python makes it easy to work with JSON records. This module ought to be incorporated (inherent) inside Python establishment, and don't have to introduce any outside modules. The main thing require with a specific end goal to utilize this module is to import it.
JSON to Python: Perusing JSON implies changing over JSON into a Python esteem. As specified over, the json library parses JSON into a word reference or rundown in Python. Keeping in mind the end goal to do that, client require the
loads()
function (load from a string).
[html]
import json
jsonData = '{"name": "Frank", "age": 39}'
jsonToPython = json.loads(jsonData)
[/html]
Python to JSON : The method
dumps()
will be used to convert from python to JSON.
[html]
import json
pythonDictionary = {'name':'Bob', 'age':44, 'isEmployed':True}
dictionaryToJson = json.dumps(pythonDictionary)
[/html]
The functionality of the function
encode()
is to convert the Python object into the string format of the JSON. Following is the syntax for the encode() function.
[html]demjson.encode(self, obj, nest_level=0)[/html]
Following is an example.
[html]
#!/usr/bin/python
import demjson
data = [ { 'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5 } ]
json = demjson.encode(data)
print json
[/html]
In the above example, demson is nothing but the module of Python for decoding , encoding and for the purpose of syntax checking.
Output: Now compile the code result will be as follows.
[html][{"a":1,"b":2,"c":3,"d":4,"e":5}][/html]
The functionality of the function
decode()
is to convert the string format of the JSON into python object. Following is the syntax for the decode() function.
[html]demjson.decode(self, txt)[/html]
Following is an example.
[html]
#!/usr/bin/python
import demjson
json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
text = demjson.decode(json)
print text
[/html]
In the above example,
demson
is nothing but the module of Python for decoding , encoding and for the purpose of syntax checking.
Output: Now compile the code result will be as follows.
[html]{u'a': 1, u'c': 3, u'b': 2, u'e': 5, u'd': 4}[/html]