I try to read an Openstreetmaps API output JSON string, which is valid.
I am using following code:
import pandas as pd
import requests
# Links unten
minLat = 50.9549
minLon = 13.55232
# Rechts oben
maxLat = 51.1390
maxLon = 13.89873
osmrequest = {'data': '[out:json][timeout:25];(node["highway"="bus_stop"](%s,%s,%s,%s););out body;>;out skel qt;' % (minLat, minLon, maxLat, maxLon)}
osmurl = 'http://overpass-api.de/api/interpreter'
osm = requests.get(osmurl, params=osmrequest)
osmdata = osm.json()
osmdataframe = pd.read_json(osmdata)
which throws following error:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-66-304b7fbfb645> in <module>()
----> 1 osmdataframe = pd.read_json(osmdata)
/Users/paul/anaconda/lib/python2.7/site-packages/pandas/io/json.pyc in read_json(path_or_buf, orient, typ, dtype, convert_axes, convert_dates, keep_default_dates, numpy, precise_float, date_unit)
196 obj = FrameParser(json, orient, dtype, convert_axes, convert_dates,
197 keep_default_dates, numpy, precise_float,
--> 198 date_unit).parse()
199
200 if typ == 'series' or obj is None:
/Users/paul/anaconda/lib/python2.7/site-packages/pandas/io/json.pyc in parse(self)
264
265 else:
--> 266 self._parse_no_numpy()
267
268 if self.obj is None:
/Users/paul/anaconda/lib/python2.7/site-packages/pandas/io/json.pyc in _parse_no_numpy(self)
481 if orient == "columns":
482 self.obj = DataFrame(
--> 483 loads(json, precise_float=self.precise_float), dtype=None)
484 elif orient == "split":
485 decoded = dict((str(k), v)
TypeError: Expected String or Unicode
How to modify the request or Pandas read_json
, to avoid an error? By the way, what's the problem?
If you print the json string to a file,
you'll see something like this:
If the JSON string were to be converted to a Python object, it would be a dict whose
elements
key is a list of dicts. The vast majority of the data is inside this list of dicts.This JSON string is not directly convertible to a Pandas object. What would be the index, and what would be the columns? Surely you don't want
[u'elements', u'version', u'osm3s', u'generator']
to be the columns, since almost all the information is in theelements
list-of-dicts.But if you want the DataFrame to consist of the data only in the
elements
list-of-dicts, then you'd have to specify that, since Pandas can't make that assumption for you.Further complicating things is that each dict in
elements
is a nested dict. Consider the first dict inelements
:Should
['lat', 'lon', 'type', 'id', 'tags']
be the columns? That seems plausible, except that thetags
column would end up being a column of dicts. That's usually not very useful. It would be nicer perhaps if the keys inside thetags
dict were made into columns. We can do that, but again we have to code it ourselves since Pandas has no way of knowing that's what we want.yields