Error when parsing JSON data
Asked Answered
B

2

8

I want to get elevation data from Google Earth according to latitude and longitude, but I am not able to 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 the error I get is :

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 appreciated.

Bedwarmer answered 3/8, 2011 at 9:45 Comment(0)
C
11

Post is a little 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))
Closestool answered 15/5, 2012 at 4:34 Comment(0)
I
6

In Python 3, binary data, such as the raw response of a http request, is stored in bytes objects. json/simplejson expects strings. The solution is to decode the bytes data to string data with the appropriate encoding, which you can find in the header.

You find the encoding with:

encoding = req.headers.get_content_charset()

You then make the content a string by:

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

This body you then can pass to the json loader.

(Also, please stop calling the response "req". It's confusing, and makes it sounds like it is a request, which it isn't.)

Iams answered 3/8, 2011 at 10:6 Comment(3)
i can't understand that where i put the change.Bedwarmer
hi regebro, pl. direct me of below code that where i am wrong.Bedwarmer
@user876307: There is not "a change", there are several needed. First you need to figure out what encoding the response is in. I'll update the answer. Also, there is no point in writing 4 comments. One would have been quite enough.Iams

© 2022 - 2024 — McMap. All rights reserved.