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

#
# 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脚本中的对象。


当前回答

没有必要使用额外的库来解析json…

Json.loads()返回一个字典。

在你的例子中,只需输入text["someValueKey"]

其他回答

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

#!/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))

请参见:JSON的读写示例

调用urlopen()所做的(根据文档)就是返回一个类文件对象。一旦你有了这个,你需要调用它的read()方法来在网络上实际拉出JSON数据。

喜欢的东西:

jsonurl = urlopen(url)

text = json.loads(jsonurl.read())
print text

你可以使用json.dumps:

import json

# Hier comes you received data

data = json.dumps(response)

print(data)

对于加载json并将其写入文件,下面的代码是有用的:

data = json.loads(json.dumps(Response, sort_keys=False, indent=4))
with open('data.json', 'w') as outfile:
json.dump(data, outfile, sort_keys=False, indent=4)

没有必要使用额外的库来解析json…

Json.loads()返回一个字典。

在你的例子中,只需输入text["someValueKey"]

我猜你实际上想从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...