在 Python 中将字符串转换为 JSON?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/16577632/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert string to JSON in Python?
提问by bnlucas
I'm trying to convert a string, generated from an http request with urllib3.
我正在尝试使用 urllib3 转换从 http 请求生成的字符串。
Traceback (most recent call last):
  File "<pyshell#16>", line 1, in <module>
    data = json.load(data)
  File "C:\Python27\Lib\json\__init__.py", line 286, in load
    return loads(fp.read(),
AttributeError: 'str' object has no attribute 'read'
>>> import urllib3
>>> import json
>>> request = #urllib3.request(method, url, fields=parameters)
>>> data = request.data
Now... When trying the following, I get that error...
现在...尝试以下操作时,我收到该错误...
>>> json.load(data) # generates the error
>>> json.load(request.read()) # generates the error
Running type(data)and type(data.read())both return <type 'str'>
运行type(data)并type(data.read())返回<type 'str'>
data = '{"subscriber":"0"}}\n'
采纳答案by Blender
json.loadloads from a file-like object. You either want to use json.loads:
json.load从类文件对象加载。你要么想使用json.loads:
json.loads(data)
Or just use json.loadon the request, which is a file-like object:
或者只是json.load在请求上使用,它是一个类似文件的对象:
json.load(request)
Also, if you use the requestslibrary, you can just do:
此外,如果您使用请求库,您可以这样做:
import requests
json = requests.get(url).json()

