Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting fields from JSON output

Tags:

python

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 
like image 522
thclpr Avatar asked Oct 17 '12 12:10

thclpr


People also ask

How do I get a specific field in JSON?

We can parse a JSON response and get a particular field from Response in Rest Assured. This is done with the help of the JSONPath class. To parse a JSON response, we have to first convert the response into a string. To obtain the response we need to use the methods - Response.

How do I query JSON data?

To query JSON data, you can use standard T-SQL. If you must create a query or report on JSON data, you can easily convert JSON data to rows and columns by calling the OPENJSON rowset function. For more information, see Convert JSON Data to Rows and Columns with OPENJSON (SQL Server).


2 Answers

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 '' 
like image 111
bohney Avatar answered Nov 05 '22 06:11

bohney


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'] 
like image 39
user8472 Avatar answered Nov 05 '22 04:11

user8472