Car*_*ary 0 python google-maps
我试图从谷歌地图请求中获取一些数据;它返回了以下数据。它以某种方式以 'b' 字符开头:
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'
Run Code Online (Sandbox Code Playgroud)
然后我试图从数据中获取一个值,它因为开头的 'b' 而出错。如果我删除'b',它工作正常:
response = str(urllib.request.urlopen(url).read())
result = json.loads(response.replace('\\n', ''))
Run Code Online (Sandbox Code Playgroud)
Python 中有没有办法在不删除“b”的情况下检索值?
你不需要b,它只是表明它是一个字节文字。
无论如何,听起来您正在使用 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)
Run Code Online (Sandbox Code Playgroud)
在 Python3 中,您必须将字节解码为字符集,或者删除 b,就像您正在做的那样:
json.loads(res.decode("utf-8"))
Run Code Online (Sandbox Code Playgroud)