首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何将网页中的JSON转换为Python脚本

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

Stack Overflow用户
提问于 2012-10-19 07:20:37
回答 10查看 476.6K关注 0票数 232

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

代码语言:javascript
复制
#
# 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

我想要做的就是将我在Firefox中加载的{{.....etc.....}}内容加载到我的脚本中,这样我就可以从中解析出一个值。我用谷歌搜索了很多次,但我还没有找到一个好的答案,那就是如何将以.json结尾的网址中的{{...}}内容转换为Python脚本中的对象。

EN

回答 10

Stack Overflow用户

发布于 2012-10-19 07:26:29

我猜想您实际上是想从URL获取数据:

代码语言:javascript
复制
jsonurl = urlopen(url)
text = json.loads(jsonurl.read()) # <-- read from it

或者,查看requests库中的JSON decoder

代码语言:javascript
复制
import requests
r = requests.get('someurl')
print r.json() # if response type was set to JSON, then you'll automatically have a JSON response here...
票数 149
EN

Stack Overflow用户

发布于 2015-03-01 04:40:57

这将从包含Python 2.X和Python 3.x的网页中获取JSON格式的字典:

代码语言:javascript
复制
#!/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

import json


def get_jsonparsed_data(url):
    """
    Receive the content of ``url``, parse it as JSON and return the object.

    Parameters
    ----------
    url : str

    Returns
    -------
    dict
    """
    response = urlopen(url)
    data = response.read().decode("utf-8")
    return json.loads(data)


url = ("http://maps.googleapis.com/maps/api/geocode/json?"
       "address=googleplex&sensor=false")
print(get_jsonparsed_data(url))

另请参阅:Read and write example for JSON

票数 32
EN

Stack Overflow用户

发布于 2016-02-24 03:59:52

我发现在使用Python 3时,这是从网页中获取JSON的最简单、最有效的方法:

代码语言:javascript
复制
import json,urllib.request
data = urllib.request.urlopen("https://api.github.com/users?since=100").read()
output = json.loads(data)
print (output)
票数 28
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12965203

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档