2016/11/22

How to convert string data into JSON object and extract data from it

This post is about how to convert string data into JSON object and extract data from it

Python Script




 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import urllib
body="%7B%22type%22%3A%22change%22%2C%22url%22%3A%22http%3A%2F%2Fapi.pachube.com%2Fv2%2Ftriggers%2F4100%22%2C%22environment%22%3A%7B%22feed%22%3A%22http%3A%2F%2Fapi.pachube.com%2Fv2%2Ffeeds%2F36133%22%2C%22title%22%3A%22Current+Cost+Bridge%22%2C%22description%22%3Anull%2C%22id%22%3A36133%7D%2C%22threshold_value%22%3Anull%2C%22timestamp%22%3A%222012-01-05T09%3A27%3A01Z%22%2C%22triggering_datastream%22%3A%7B%22url%22%3A%22http%3A%2F%2Fapi.pachube.com%2Fv2%2Ffeeds%2F36133%2Fdatastreams%2F1%22%2C%22value%22%3A%7B%22value%22%3A%22523%22%2C%22max_value%22%3A1269.0%2C%22min_value%22%3A0.0%7D%2C%22id%22%3A%221%22%2C%22units%22%3A%7B%22symbol%22%3A%22W%22%2C%22type%22%3A%22derivedUnits%22%2C%22label%22%3A%22watts%22%7D%7D%2C%22id%22%3A4100%7D"
unquoted = urllib.unquote(body)

import json
pythonDict = json.loads(unquoted)
print(pythonDict)

print("")
print(pythonDict['threshold_value'])
print(pythonDict['url'])
print(pythonDict['timestamp'])

env = pythonDict['environment']
print(env['feed'])
print(env['id'])
print(env['description'])
print(env['title'])

print(pythonDict['type'])
print(pythonDict['id'])

tri = pythonDict['triggering_datastream']
print(tri['url'])

uni = tri['units']
print(uni['symbol'])
print(uni['type'])
print(uni['label'])

print(tri['id'])

val = tri['value']
print(val['max_value'])
print(val['min_value'])
print(val['value'])

Content of "unquoted"

{u'threshold_value': None, u'url': u'http://api.pachube.com/v2/triggers/4100', u'timestamp': u'2012-01-05T09:27:01Z', u'environment': {u'feed': u'http://api.pachube.com/v2/feeds/36133', u'id': 36133, u'description': None, u'title': u'Current+Cost+Bridge'}, u'type': u'change', u'id': 4100, u'triggering_datastream': {u'url': u'http://api.pachube.com/v2/feeds/36133/datastreams/1', u'units': {u'symbol': u'W', u'type': u'derivedUnits', u'label': u'watts'}, u'id': u'1', u'value': {u'max_value': 1269.0, u'min_value': 0.0, u'value': u'523'}}}

Organized "unquoted" (for easy reading)


Result



Reference:

How to convert a string data to a JSON object in python?
http://stackoverflow.com/questions/8740353/how-to-convert-a-string-data-to-a-json-object-in-python

No comments:

Post a Comment