我是學習 python 請求的新手,我正在使用GETMETHOD,我試圖在串列中插入回傳的 json 內容,但它正在顯示
TypeError:位元組型別的物件不是 JSON 可序列化的
我已經嘗試過很多次,我也嘗試過添加到字典中。
視圖.py
def request_get(request):
url = "http://127.0.0.1:8000/api/items/"
response = requests.get(url)
results = []
results.append(response.content)
return redirect('home')
但它顯示TypeError: Object of type bytes is not JSON serializable
我也嘗試過使用:-
results = []
results.append({
'response' : response.content
})
完整回溯
Traceback (most recent call last):
File "D:\apps - app\app\env\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
response = get_response(request)
File "D:\apps - app\app\env\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\app - app - app\env\lib\site-packages\django\http\response.py", line 653, in __init__
data = json.dumps(data, cls=encoder, **json_dumps_params)
File "C:\Users\AppData\Local\Programs\Python\Python310\lib\json\__init__.py", line 238, in dumps
**kw).encode(obj)
File "C:\Users\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "C:\Users\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "D:\app - app - app\env\lib\site-packages\django\core\serializers\json.py", line 106, in default
return super().default(o)
File "C:\Users\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type bytes is not JSON serializable
但它也沒有為我作業。
任何幫助將非常感激。先感謝您
uj5u.com熱心網友回復:
您需要使用results.append(response.json())轉換為JSON
或嘗試:
import json
results.append(json.loads(response.content.decode("utf-8")))
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/453292.html
下一篇:進行遷移未檢測模型中的多對多欄位
