[英]Return HTTP json response
我是使用 python 開發 REST API 的新手。 我想將此列表返回為 json 作為響應。 我使用來自 sanic 的響應。
response_data = [{'error': False, 'errormsg': '', 'status': '200'}, {'data': {1: {'name': 'sosialisasi', 'm_value': 77, 'c_value': 876, 'cu_value': 568, 'cl_value': 468, 'independent_vars': {'jumlah hari': {None: {'val_name': None, 'value': None}}, 'tingkatan sosialisasi': {2: {'val_name': 'kecamatan', 'value': '0.5'}, 1: {'val_name': 'kabupaten', 'value': '0.75'}}}}}}]
response.json(response_data, 200)
但我收到錯誤TypeError: expected bytes, str found
Traceback (most recent call last):
File "/home/dewi/saniccrudenv/lib/python3.8/site-packages/sanic/app.py", line 939, in handle_request
response = await response
File "/home/dewi/anomali/operations.py", line 183, in getAsb
return response.json(response_data, 200)
File "/home/dewi/saniccrudenv/lib/python3.8/site-packages/sanic/response.py", line 210, in json
dumps(body, **kwargs),
TypeError: expected bytes, str found
我的代碼有問題嗎? 當我在 response_data 上使用 json.dumps 時,這不是錯誤。 但它會像這樣返回 json 字符串
"[{\"error\": false, \"errormsg\": \"\", \"status\": \"200\"}, {\"data\": {\"1\": {\"name\": \"sosialisasi\", \"m_value\": 77, \"c_value\": 876, \"cu_value\": 568, \"cl_value\": 468, \"independent_vars\": {\"jumlah hari\": {\"null\": {\"val_name\": null, \"value\": null}}, \"tingkatan sosialisasi\": {\"2\": {\"val_name\": \"kecamatan\", \"value\": \"0.5\"}, \"1\": {\"val_name\": \"kabupaten\", \"value\": \"0.75\"}}}}}}]"
我想要的是json object,像這樣
[
{
"error": false,
"errormsg": "",
"status": "200"
},
{
"data": [
{
"id": 1,
"nama": "test1",
"kode": "101"
},
{
"id": 2,
"nama": "test2",
"kode": "202"
}
]
}
]
問題是您將None
作為關鍵字:
response_data = [
{"error": False, "errormsg": "", "status": "200"},
{
"data": {
1: {
"name": "sosialisasi",
"m_value": 77,
"c_value": 876,
"cu_value": 568,
"cl_value": 468,
"independent_vars": {
"jumlah hari": {
None: {"val_name": None, "value": None}
},
"tingkatan sosialisasi": {
2: {"val_name": "kecamatan", "value": "0.5"},
1: {"val_name": "kabupaten", "value": "0.75"},
},
},
}
}
},
]
如果你改變:
"jumlah hari": {
None: {"val_name": None, "value": None}
},
至
"jumlah hari": {
"None": {"val_name": None, "value": None}
},
它將按預期工作。
$ curl localhost:9999/ (env: sanic)
[{"error":false,"errormsg":"","status":"200"},{"data":{"1":{"name":"sosialisasi","m_value":77,"c_value":876,"cu_value":568,"cl_value":468,"independent_vars":{"jumlah hari":{"None":{"val_name":null,"value":null}},"tingkatan sosialisasi":{"2":{"val_name":"kecamatan","value":"0.5"},"1":{"val_name":"kabupaten","value":"0.75"}}}}}}]
object 結構表示為一對圍繞零個或多個名稱/值對的花括號標記。 名稱是一個字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.