Thales Pereira Thales Pereira - 1 year ago 132
Python Question

Selecting fields from JSON output

Using Python, how can i extract the field

to a variable? Basicaly, i to transform this:

"accountWide": true,
"criteria": [
"description": "some description",
"id": 7553,
"max": 1,
"orderIndex": 0

to something like

print "Description is: " + description
print "ID is: " + id
print "Max value is : " + max

Answer Source

Assume you stored that dictionary in a variable called values. To get id in to a variable, do:

idValue = values['criteria'][0]['id']

If that json is in a file, do the following to load it:

import json
jsonFile = open('your_filename.json', 'r')
values = json.load(jsonFile)

If that json is from a URL, do the following to load it:

import urllib, json
f = urllib.urlopen("http://domain/path/jsonPage")
values = json.load(f)

To print ALL of the criteria, you could:

for criteria in values['criteria']:
    for key, value in criteria.iteritems():
        print key, 'is:', value
    print ''
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download