谷歌地图响应以' b'开始,如何检索数据?

时间:2016-02-16 05:00:44

标签: python google-maps

我尝试从Google地图请求中获取一些数据;它返回了以下数据。它始于''人物不知何故:

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'

然后我试图从数据中获取一个值,因为' b'在开始。如果我删除''它可以正常工作:

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

Python中是否有办法在不删除' b'的情况下检索值?

2 个答案:

答案 0 :(得分:1)

您不需要b,只是表示它是bytes literal

无论如何,这听起来像是在使用Python3,因为在Python2中,这很好用:

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)

在Python3中,您必须将字节解码为字符集,或者删除b,就像您正在做的那样:

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

答案 1 :(得分:0)

您需要将bytes对象解码为string:

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

我希望它适合你。