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

#
# 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

我要做的是获得{{.....等.....}}东西,我看到的URL,当我在Firefox加载到我的脚本,所以我可以解析出一个值。我已经谷歌了很多,但我还没有找到一个很好的答案,如何实际得到{{…}}将以.json结尾的URL转换为Python脚本中的对象。


当前回答

对于python>=3.6,您可以使用:

import dload

j = dload.json(url)

安装dload:

pip3 install dload

其他回答

从URL获取数据,然后调用json。加载。

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" ]
        },
        {
...

我猜你实际上想从URL中获取数据:

jsonurl = urlopen(url)
text = json.loads(jsonurl.read()) # <-- read from it

或者,在请求库中查看JSON解码器。

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...

你需要导入请求并使用from json()方法:

source = requests.get("url").json()
print(source)

当然,这个方法也适用:

import json,urllib.request
data = urllib.request.urlopen("url").read()
output = json.loads(data)
print (output)

json。load将使用此表将其解码为Python对象,例如JSON对象将成为Python dict。

在Python 2中,json.load()可以代替json.loads()

import json
import urllib

url = 'https://api.github.com/users?since=100'
output = json.load(urllib.urlopen(url))
print(output)

不幸的是,这在Python 3中不起作用。json。Load只是对json的包装。为类文件对象调用read()的加载。json。load需要一个字符串对象,urllib.urlopen(url).read()的输出是一个字节对象。因此,为了使它在python3中工作,必须获得文件编码。

在本例中,我们查询编码头,如果没有得到编码头,则退回到utf-8。在Python 2和3中,headers对象是不同的,所以它必须以不同的方式完成。使用请求可以避免这一切,但有时需要坚持使用标准库。

import json
from six.moves.urllib.request import urlopen

DEFAULT_ENCODING = 'utf-8'
url = 'https://api.github.com/users?since=100'
urlResponse = urlopen(url)

if hasattr(urlResponse.headers, 'get_content_charset'):
    encoding = urlResponse.headers.get_content_charset(DEFAULT_ENCODING)
else:
    encoding = urlResponse.headers.getparam('charset') or DEFAULT_ENCODING

output = json.loads(urlResponse.read().decode(encoding))
print(output)

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

import json,urllib.request
data = urllib.request.urlopen("https://api.github.com/users?since=100").read()
output = json.loads(data)
print (output)