Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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("http://api.inaturalist.org/v1/observations?place_id=6924&taxon_id=20856&per_page=200&order=desc&order_by=created_at")
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:

9.5142456535,-83.8011438905
10.2335478381,-84.8517773638
10.3358965682,-84.9964271008
10.3744851815,-84.9871494128
10.2468720343,-84.9298072822
...

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.

like image 815
Anthony W Avatar asked Sep 19 '25 02:09

Anthony W


1 Answers

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

for item in obSet['results']:
    print(item['location'])

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.

like image 147