Error parsing JSON data

I want to get altitude data from Google Earth according to latitude and longitude, but I cannot do this. I'm not sure what I'm doing wrong, but my code is shown below.

def getElevation(locations,sensor="true", **elvtn_args): elvtn_args.update({ 'locations': locations, 'sensor': sensor }) url = ELEVATION_BASE_URL params = urllib.parse.urlencode(elvtn_args) baseurl = url +"?"+ params; req = urllib.request.urlopen(str(baseurl)); response = simplejson.load(req); 

And I get the error:

 Traceback (most recent call last): File "D:\GIS\Arctools\ElevationChart - Copy.py", line 85, in <module> getElevation(pathStr) File "D:\GIS\Arctools\ElevationChart - Copy.py", line 45, in getElevation response = simplejson.load(req); File "C:\Python32\lib\json\__init__.py", line 262, in load parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw) File "C:\Python32\lib\json\__init__.py", line 307, in loads return _default_decoder.decode(s) File "C:\Python32\lib\json\decoder.py", line 351, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) TypeError: can't use a string pattern on a bytes-like object 

Any help was appreciated.

+8
python google-api google-earth
source share
2 answers

The message is a bit late, but recently ran into the same problem. The solution below worked for me. Basically what Lennart said.

 from urllib import request import json req = request.urlopen('https://someurl.net/api') encoding = req.headers.get_content_charset() obj = json.loads(req.read().decode(encoding)) 
+11
source share

In Python 3, binary data, such as the raw response of an HTTP request, is stored in byte objects. json / simplejson is expecting a string. The solution is to decode the byte data into string data with the appropriate encoding, which you can find in the header.

You will find the encoding with:

 encoding = req.headers.get_content_charset() 

Then you create the content as a string:

 body = req.readall().decode(encoding) 

In this body, you can go to the json loader.

(Also, stop calling the answer β€œreq.” This is confusing and makes it sound like it's a query that isn't there.)

+6
source share

All Articles