49

Using Python, how can i extract the field id 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
Serenity
  • 35,289
  • 20
  • 120
  • 115
thclpr
  • 5,778
  • 10
  • 54
  • 87
  • 2
    You could have a look at http://docs.python.org/library/json.html Everything can be found there. – cb0 Oct 17 '12 at 12:53

2 Answers2

61

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)
jsonFile.close()

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)
f.close()

To print ALL of the criteria, you could:

for criteria in values['criteria']:
    for key, value in criteria.iteritems():
        print key, 'is:', value
    print ''
bohney
  • 1,187
  • 8
  • 12
  • Hi, in fact it is an http output. i will try to convert your example to parse the output from the website. – thclpr Oct 17 '12 at 13:10
  • 1
    @Thales See the example section of: http://docs.python.org/library/urllib.html#examples Take the value returned by `urllib.urlopen` and pass that to `json.load` in place of `jsonFile` my example above. – bohney Oct 17 '12 at 13:23
13

Assuming you are dealing with a JSON-string in the input, you can parse it using the json package, see the documentation.

In the specific example you posted you would need

x = json.loads("""{
 "accountWide": true,
 "criteria": [
     {
         "description": "some description",
         "id": 7553,
         "max": 1,
         "orderIndex": 0
     }
  ]
 }""")
description = x['criteria'][0]['description']
id = x['criteria'][0]['id']
max = x['criteria'][0]['max']
user8472
  • 3,268
  • 3
  • 35
  • 62