Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error when parsing JSON data

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.

like image 563
user876307 Avatar asked Aug 03 '11 09:08

user876307


People also ask

How do you handle JSON parsing error?

The most common way to handle JSON parse error is using try-catch block. If the JSON string is valid, it will return a JavaScript object. If the JSON string is invalid, it will throw a SyntaxError.

How do I fix JSON format error?

Follow these steps to resolve your invalid JSON formatting error. Verify that the service account credentials are in a valid JSON format. Tip: An online JSON formatter can identify problems with the JSON format. If the error persists, generate a new service account credentials key.

What does error parsing JSON response mean?

It means that the editor failed to get a response to the server or the response wasn't in a valid JSON format. Basically, if the editor can't communicate with the server, it will show this error message instead.

What is JSON data error?

In cases where a JavaScript Object Notation (JSON) transaction fails, the API Gateway can use a JSON Error to convey error information to the client. By default, the API Gateway returns a very basic fault to the client when a message filter has failed.


1 Answers

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))
like image 118
jdsantiagojr Avatar answered Oct 28 '22 19:10

jdsantiagojr