我是使用python开发RESTAPI的新手。 我想将此列表作为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
我的代码有问题吗? 当我在响应_数据上使用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对象,类似这样的东西
[
{
"error": false,
"errormsg": "",
"status": "200"
},
{
"data": [
{
"id": 1,
"nama": "test1",
"kode": "101"
},
{
"id": 2,
"nama": "test2",
"kode": "202"
}
]
}
]
问题是您将
None
作为关键字:如果您更改:
到
它将按预期工作
JSON规范:
Source
相关问题 更多 >
编程相关推荐