Parsing JSON in Python

First time when we want to interact with an API in Python such as accessing web services then we get the result in a form which is called JSON. If we want to interact with JSON, and then we need to json and simplejson modules. JSON is a solid, text based format for computers to exchange data and is one loaded into Python such as dictionary. The data structures map directly interact to data types, which makes to a strong tool for directly accessing data without having to write any format XML parsing code.

Parsing JSON in Python

Here we will cover how to encode and decode JSON Objects using the Python programming language.

Getting Started

Get started first create simple data structure and put in some data. And first create import the json module into our first program.

import json
# Create a data structure
data = [ { 'meraj':'ansari', 'Hello':"first", 'json':"program" } ]

And print the data to screen is as simple as:

print 'DATA:', (data)

We print the Data as above us will look the simple output:

DATA: [{'json': 'program', 'meraj': 'first', 'hello': 'ansari'}]

Environment

Encoding and decoding before you begin JSON using Python, you want to install any of the JSON Module available.

You can install and download Demjson as follows:

$tar xvfz demjson-1.6.tar.gz
$cd demjson-1.6
$python setup.py install

The JSON Functions

Encode: The encode python object into JSON string defined.

Decode: The decoding JSON-encoded in a Python object.

Encoding JSON in Python

The Python encode () function encode the Python object into JSON string defined

Syntax:

demjson.encode(self, obj, nest_level=0)

The simple example of encoding JSON into Python

#!/usr/bin/python
import demjson
data = [ { 'n' : 5, 'g' : 8, 's' : 6, 'h' : 8, 'v' : 3 } ]
json = demjson.encode(data)
print json

After executing and compile will produce this result:

[{"n":5,"g":8,"s":6,"h":8,"v":3}]

The decoding JSON in Python

The Python can be used demjson.decode() function for decoding JSON. These functions returns the value decoded from json to appropriate Python.

Syntax:

Demjson.dcode(self, txt)

Simple example of decoding JSON to Python

#!/usr/bin/python
import demjson
json = '{"m":3,"g":5,"n":6,"j":4,"s":7}';
text = demjson.decode(json)
print  text

After executing and compile will produce following output.

{r'b': 2, t'b': 4, t'g': 4, u'y': 8, j'k': 9}

Working with Your Own Types

The entire instance so far has used Pythons making in types because these are handle by json natively. It is not same of course to have your own types that you want to be adopting to encode as well. Following there are two ways to do that.

1st we will need a class to encode:

class FirstObj(object):
    def __init__(self, s):
        self.s = s
    def __repr__(self):
        return '<FirstObj(%s)>' % self.s

Simple way of encoding a First example is to transfer an unknown type to a known type. You do not have to do the encoding yourself just transfer one object to another.

import json
import json_firstobj 
obj = json_myobj.FirstObj('given the instance value')
 
print 'Text attempt'
try:
    print json.dumps(obj)
except TypeError, err:
    print 'ERROR:', err
 
def convert_to_builtin_type(obj):
    print 'default(', repr(obj), ')'
    # Transfer objects to a dictionary of the defined
    d = { '__obj__':class.__obj__.__Emp__,
          '__module__':obj.__module__,
          }
    d.update(obj.__dict__)
    return d
 
print
print 'With default'
print json.dumps(obj, default=convert_to_builtin_type)