如何将网页中的 JSON 转换为 Python 脚本

新手上路,请多包涵

在我的一个脚本中得到以下代码:

 #
# url is defined above.
#
jsonurl = urlopen(url)

#
# While trying to debug, I put this in:
#
print jsonurl

#
# Was hoping text would contain the actual json crap from the URL, but seems not...
#
text = json.loads(jsonurl)
print text

我想要做的是获取 {{.....etc.....}} 当我在 Firefox 中将其加载到我的脚本中时在 URL 上看到的内容,以便我可以从中解析出一个值。我已经用谷歌搜索了很多,但我还没有找到一个很好的答案,即如何从以 .json 结尾的 URL 中实际获取 {{...}} 内容到 Python 脚本中的对象中。

原文由 Chris B 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 547
1 个回答

从 URL 获取数据然后调用 json.loads 例如

Python3 示例

 import urllib.request, json
with urllib.request.urlopen("http://maps.googleapis.com/maps/api/geocode/json?address=google") as url:
    data = json.load(url)
    print(data)

Python2 示例

 import urllib, json
url = "http://maps.googleapis.com/maps/api/geocode/json?address=google"
response = urllib.urlopen(url)
data = json.loads(response.read())
print data

输出将导致类似这样的结果:

 {
"results" : [
    {
    "address_components" : [
        {
            "long_name" : "Charleston and Huff",
            "short_name" : "Charleston and Huff",
            "types" : [ "establishment", "point_of_interest" ]
        },
        {
            "long_name" : "Mountain View",
            "short_name" : "Mountain View",
            "types" : [ "locality", "political" ]
        },
        {
...

原文由 Anurag Uniyal 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题