tonglei100 / sweetest

小而美的自动化测试解决方案,支持 Web UI 测试,Http 接口测试,DB 操作测试,App 测试,小程序测试,Windows GUI 测试,文件操作

Home Page:https://sweeter.io

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

如下这种返回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,确实解决了这个问题
不过,作为框架还需要更好的通用性,我后面好好想想...