[英]Convert string to JSON in Python?
我正在嘗試轉換使用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
現在......當嘗試以下內容時,我得到了這個錯誤......
>>> json.load(data) # generates the error
>>> json.load(request.read()) # generates the error
運行type(data)
和type(data.read())
都返回<type 'str'>
type(data.read())
<type 'str'>
data = '{"subscriber":"0"}}\n'
json.load
從類文件對象加載。 你想要使用json.loads
:
json.loads(data)
或者只是在請求上使用json.load
,這是一個類似文件的對象:
json.load(request)
此外,如果您使用請求庫,您可以這樣做:
import requests
json = requests.get(url).json()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.