Cary
Cary

Reputation: 21

google maps response starts with 'b', how can I retrieve the data?

I tried to get some data from a Google maps request; it returned the following data. It starts with a 'b' character somehow:

b'{
    \n "destination_addresses" : [ "Toronto, ON, Canada" ],
    \n "origin_addresses" : [ "Ottawa, ON, Canada" ],
    \n "rows" : [\n {
        \n "elements" : [\n {
            \n "distance" : {
                \n "text" : "450 km",
                \n "value" : 449678\n
            },
            \n "duration" : {
                \n "text" : "4 hours 14 mins",
                \n "value" : 15229\n
            },
            \n "status" : "OK"\n
        }\n ]\n
    }\n   ],
    \n   "status" : "OK"\n
}\n'

Then I tried to get a value from the data, it errors because of the 'b' at the beginning. If I remove the 'b', it works fine:

response = str(urllib.request.urlopen(url).read())
result = json.loads(response.replace('\\n', ''))

Is there a way in Python to retrieve the values without removing the 'b'?

Upvotes: 1

Views: 4036

Answers (3)

Sikandar Khan
Sikandar Khan

Reputation: 11

Simple! I'm assuming you are using python requests library.

response = requests.get(url,headers)

now if your output contains b that means its byte literal

just convert it to json like that

response = response.json()

Upvotes: 1

the_unknown_spirit
the_unknown_spirit

Reputation: 2586

you need to decode the bytes object to string as :

result  = json.loads(response.decode("utf-8"))

I hope it works for you.

Upvotes: 0

rofls
rofls

Reputation: 5115

You don't need the b, it just indicates that it's a bytes literal.

Anyway it sounds like you're using Python3, since in Python2, this works fine:

res = b'{\n "destination_addresses" : [ "Toronto, ON, Canada" ],\n "origin_addresses" : [ "Ottawa, ON, Canada" ],\n "rows" : [\n {\n "elements" : [\n {\n "distance" : {\n "text" : "450 km",\n "value" : 449678\n },\n "duration" : {\n "text" : "4 hours 14 mins",\n "value" : 15229\n },\n "status" : "OK"\n }\n ]\n }\n ],\n "status" : "OK"\n}\n'
json.loads(res)

In Python3 you would have to decode the bytes into a character set, or remove the b, like you're doing:

json.loads(res.decode("utf-8"))

Upvotes: 6

Related Questions