How to parse data in JSON format? How to parse data in JSON format? python python

How to parse data in JSON format?


Very simple:

import jsondata = json.loads('{"one" : "1", "two" : "2", "three" : "3"}')print data['two']


Sometimes your json is not a string. For example if you are getting a json from a url like this:

j = urllib2.urlopen('http://site.com/data.json')

you will need to use json.load, not json.loads:

j_obj = json.load(j)

(it is easy to forget: the 's' is for 'string')


For URL or file, use json.load(). For string with .json content, use json.loads().

#! /usr/bin/pythonimport json# from pprint import pprintjson_file = 'my_cube.json'cube = '1'with open(json_file) as json_data:    data = json.load(json_data)# pprint(data)print "Dimension: ", data['cubes'][cube]['dim']print "Measures:  ", data['cubes'][cube]['meas']