Anthony W Anthony W - 1 year ago 212
JSON Question

Python List comprehension and JSON parsing

I'm new to Python and trying to figure out the best way to parse the values of a JSON object into an array, using a list comprehension.

Here is my code - I'm querying the publicly available iNaturalist API and would like to take the JSON object that it returns, so that I take specific parts of the JSON object into a bumpy array:

import json
import urllib2

#Set Observations URL request for Resplendent Quetzal of Costa Rica
query = urllib2.urlopen("")
obSet = json.load(query)

#Print out Lat Long of observation
n = obSet['total_results']

for i in range(n) :
print obSet['results'][i]['location']

This all works fine and gives the following output:


What I'd like to do next is replace the for loop with a list comprehension, and store the location value in a tuple. I'm struggling with the syntax in that I'm guessing it's something like this:

[(long,lat) for i in range(n) for (long,lat) in obSet['results'][i]['location']]

But this doesn't work...thanks for any help.

Answer Source

obSet['results'] is a list, no need to use range to iterate over it:

for item in obSet['results']:

To make this into list comprehension you can write:

[item['location'] for item in obSet['results']]

But, each location is coded as a string, instead of list or tuple of floats. To get it to the proper format, use

[tuple(float(coord) for coord in item['location'].split(','))
 for item in obSet['results']]

That is, split the item['location'] string into parts using , as the delimiter, then convert each part into a float, and make a tuple of these float coordinates.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download