如下这种返回json,实际上是数组的情况,怎么取[0]['id']的值呢?
hekaiyou opened this issue · comments
response json: [{'id': 1981, 'icon': 'test1', 'name': 'test1', 'directDeviceGroupId': '1', 'status': None, 'count': 0}, {'id': 1980, 'icon': 'test', 'name': 'test', 'directDeviceGroupId': '1', 'status': None, 'count': 0}]
[
{
'id': 1981,
'icon': 'test1',
'name': 'test1',
'directDeviceGroupId': '1',
'status': None,
'count': 0
},
{
'id': 1980,
'icon': 'test',
'name': 'test',
'directDeviceGroupId': '1',
'status': None,
'count': 0
}
]
这不是 json 格式,json 最外层应该是 {}
这种响应格式不太标准,目前需要写自定义函数来获取
我看这里已经转化为 python 的 list 了,请问是通过 response.json() 转化的,还是怎么来的
在keywords/http.py加了两个输出
logger.info('status_code: %s' % repr(r.status_code))
try: # json 响应
print(r.json())
print(r.json()[0])
logger.info('response json: %s' % repr(r.json()))
except: # 其他响应
logger.info('response text: %s' % repr(r.text))
输出结果如下
2020-03-09 09:40:03,211 [INFO]: # PARAMS: {'houseId': '14936', 'visible': '1'}
2020-03-09 09:40:03,212 [INFO]: # status_code: 200
[{'id': 1981, 'icon': 'test1', 'name': 'test1', 'directDeviceGroupId': '1', 'status': None, 'count': 0}, {'id': 1980, 'icon': 'test', 'name': 'test', 'directDeviceGroupId': '1', 'status': None, 'count': 0}]
{'id': 1981, 'icon': 'test1', 'name': 'test1', 'directDeviceGroupId': '1', 'status': None, 'count': 0}
2020-03-09 09:40:03,307 [INFO]: # response json: [{'id': 1981, 'icon': 'test1', 'name': 'test1', 'directDeviceGroupId': '1', 'status': None, 'count': 0}, {'id': 1980, 'icon': 'test', 'name': 'test', 'directDeviceGroupId': '1', 'status': None, 'count': 0}]
确实在这一步通过 response.json() 转化成json格式
OK 我知道了,后面看看把 list 格式也加进去
我在本地对解析的部分进行如下更改
elif v == 'text':
g.var[k] = response['text']
logger.info('%s: %s' % (k, repr(g.var[k])))
elif k == 'json':
# 从这里开始修改
sub_str = output.get('json', '{}')
if sub_str[0] == '[':
index = sub_str.split(']')[0][1:]
sub = json2dict(sub_str[len(index)+2:])
result = check(sub, response['json'][int(index)])
else:
sub = json2dict(output.get('json', '{}'))
result = check(sub, response['json'])
# logger.info('Compare json result: %s' % result)
目前通过 json=[-1]{'id':'<id1>'}
可以解决这个问题
nice,确实解决了这个问题
不过,作为框架还需要更好的通用性,我后面好好想想...