Monday, October 5, 2015

Creating and Parsing JSON

What is JSON

Before dealing with creating and parsing JSON, let’s understand what JSON is. JSON stands for JavaScript Object Notation.

Main Features of JSON:
  •          It is a lightweight data-interchange format.
  •          It is easy for humans to read and write.
  •          It is easy for machines to parse and generate.
  •          JSON is a text format that is completely language independent


Sample JSON element:
  
['{"key": 0}', '{"key": 1}', '{"key": 2}', '{"key": 3}', '{"key": 4}']

JSON is built on two structures:
  1. A collection of name/value pairs (Object)
  2. An ordered list of values


An object is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Each name is followed by: (colon) and the name/value pairs are separated by, (comma).

An array is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by, (comma).

Note you can put array inside objects and objects inside array as well. By using this combination you can pass very complex data easily.

Creating JSON Message in Python

Please note: Before you start creating a python program which would create JSON, you need to have predefined JSON format that you would expect.

I need data in following format:
[              {
"square": 1,
"key": 1
}
{ ….
}
]

Sample Program:
import json

data = {}
array = []
for i in range(0,5):
      data['square'] = i*i
      data['key'] = i
      json_data = json.dumps(data)
      array.append(json_data)

print json_data
print array

Parsing JSON Message in Python

Similar to creation of JSON, while parsing also you need to know the JSON structure. This will enable you to properly design your program that will parse the JSON
Sample program:
import json
array = ['{"square": 0, "key": 0}', '{"square": 1, "key": 1}', '{"square": 4, "key": 2}', '{"square": 9, "key": 3}', '{"square": 16, "key": 4}']
print array
print "*****************now parsing the data"
for i in range(0,5):
      parsed_json =     json.loads(array[i])
      square      =     parsed_json['square']
      key         =     parsed_json['key']
      print "squar is  :%s" % square
      print "key is    :%s" % key

No comments:

Post a Comment