问题描述
我在使用 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对象,像这样
[
{
"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,
它会按预期工作。
$ 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"}}}}}}]
JSON 规范:
一个对象结构被表示为一对围绕零个或多个名称/值对的大括号标记。名称是一个字符串。