【问题标题】:Python3 Json location data extractPython3 Json位置数据提取
【发布时间】:2020-03-19 15:48:26
【问题描述】:

大家好,感谢您的宝贵建议。我通常会找到一些帮助,所以这是我的第一个问题。经过很长时间后,我设法从这段代码中得到了可用的响应。很多文章不适用于python3。

import re
import json
import urllib.request, urllib.error, urllib.parse
import hashlib
import uuid
#! /usr/bin/env python

try:

    # For Python 3.0 and later
    from urllib.request import urlopen
except ImportError:
    # Fall back to Python 2's urllib2
    from urllib2 import urlopen

html = urlopen("http://ipinfo.io/json")

#result = html(buf.decode('utf-8'))

print(html.read())

回复以这种形式出现。

b'{\n  "ip": "84.0.23.49",\n  "hostname": "cpc127884-ldry4-2-0- 
cust47.know.cable.virginm.net",\n  "city": "London",\n  "region": 
"UK",\n  "country": "GB",\n  "loc": "54.9971,-7.3073",\n  "org": 
"AS5089 Virgin Media Limited",\n  "postal": "BT34",\n  "timezone": 
"Europe/London",\n  "readme": "https://ipinfo.io/missingauth"\n}'

我不知道这是我的位置或互联网服务,还是 RPi,或者这可能是新格式。顺便说一句,我更改了一些位置详细信息。但是似乎没有一篇文章描述如何以这种形式获取信息。它通常看起来不同。我尝试时遇到很多错误 - 例如告诉我数据是二进制而不是 str 我如何从这个“字典”中获取我的位置或城市?

【问题讨论】:

    标签: json python-3.x raspberry-pi urllib urlopen


    【解决方案1】:

    使用json.loads()函数解析json响应(你会得到Python dict):

    import json
    from urllib.request import urlopen
    
    html = urlopen("http://ipinfo.io/json")
    d = json.loads(html.read().decode('utf-8'))
    print(d['city'])
    print(d['loc'])
    

    打印(以我为例):

    Bratislava
    49.041,17.2512
    

    【讨论】:

    • 我收到以下错误:- Traceback(最近一次调用最后一次):文件“/home/pi/Desktop/testcall.py”,第 19 行,在 d = json.load( html) 文件 "/usr/lib/python3.5/json/__init__.py", 第 268 行, 在加载 parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw) 文件 "/usr/lib/python3.5/json/ __init__.py",第 312 行,在加载 s.__class__.__name__)) 类型错误:JSON 对象必须是 str,而不是 'bytes'
    • @KevinLynn 我更新了我的答案(我使用的是Python3.6,可能与Python3.5有一些差异)
    • 我试图重复定位 - Traceback File "/home/pi/Desktop/testcall.py", line 20, in lscity = json.loads(html.read().decode ('utf-8')) 文件“/usr/lib/python3.5/json/__init__.py”,第 319 行,加载返回 _default_decoder.decode(s) 文件“/usr/lib/python3.5/json /decoder.py”,第 339 行,在 decode obj 中,end = self.raw_decode(s, idx=_w(s, 0).end()) 文件“/usr/lib/python3.5/json/decoder.py ",第 357 行,在 raw_decode 中引发 JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
    • 我重复你为定位所做的事情。它可以工作 - 但是当我尝试为城市一个为 loc 制作 2 个变量时,它会因上述错误而失败
    • @KevinLynn 查看我的编辑。您不想再次读取 html 变量。只需使用带有正确键的字典d
    猜你喜欢
    • 2014-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多