python接口路径,python通过定制路径的方式解析接口返回数据

该问题基于http://stackoverflow.com/questions/7320319/xpath-like-query-for-nested-python-dictionaries的讨论,源码来自于pyresttest的实现。

问题:在做接口测试时,经常需要检查返回的json数据中某个字段是否符合预期。固然可以在代码里写死要检查的字段,但不太灵活,希望能用路径的方式来访问字段。例如如下结构的json数据,定义路径data.0.name,代表responsedata['data'][0]['name']

{

data : [

{

name : 'bob',

tel : '12345'

},

{

name : 'alice',

tel: '234565'

}

],

total : 1,

page : 1,

}

代码

def query_dictionary(query, dictionary, delimiter='.'):

""" Do an xpath-like query with dictionary, using a template if relevant """

# Based on

# http://stackoverflow.com/questions/7320319/xpath-like-query-for-nested-python-dictionaries

try:

stripped_query = query.strip(delimiter)

if stripped_query:

for x in stripped_query.split(delimiter):

try:

x = int(x)

dictionary = dictionary[x]

except ValueError:

dictionary = dictionary[x]

except:

return None

return dictionary

分析:

query_dictionary使用'.'作为路径层级之间的间隔,也可以替换成其他符号。这段代码可以满足一般接口测试的要求,

将定义的字符串和预期值写在配置文件中,无疑会带来很大的灵活性。如果你期望更强大的路径定制功能,还可以使

用第三方库jmespath,它的官网是jmespath.org

response = urllib.urlopen('your-get-url')

responsedata = json.loads(response.read())

print query_dictionary('data.0.name', responsedata)

print query_dictionary('data.1.tel', responsedata)

print query_dictionary('total')

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值