提问者:小点点

如何将网页中的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

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


共2个答案

匿名用户

从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.loads(url.read().decode())
    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

或者,在requests库中查看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...