jsonpath-rw處理Json物件
阿新 • • 發佈:2021-01-07
前提:介面自動化測試中,存在依賴情況:test_02的某個請求引數的值,需要依賴test_01返回結果中某個欄位的資料,所以就先需要拿到返回資料中特定欄位的值。這裡使用到python中jsonpath-rw庫
官方文件:https://pypi.python.org/pypi/jsonpath-rw (更多jsonpath的語法請點選連結)
參考部落格:https://www.cnblogs.com/Neeo/articles/12787888.html
1.下載安裝
pip install jsonpath-rw
2.匯入
from jsonpath_rw import jsonpath,parse
3.例子介紹
1.返回的match資料,但我們想要的是value資料
jsonpath_expr = parse('foo[*].baz') data = {'foo': [{'baz': 'news'}, {'baz': 'music'}]} print([match for match in jsonpath_expr.find(data)]) 執行結果: [DatumInContext(value='news', path=Fields('baz'), context=DatumInContext(value={'baz': 'news'}, path=<jsonpath_rw.jsonpath.Index object at 0x025CA850>, context=DatumInContext(value=[{'baz': 'news'}, {'baz': 'music'}], path=Fields('foo'), context=DatumInContext(value={'foo': [{'baz': 'news'}, {'baz': 'music'}]}, path=This(), context=None)))), DatumInContext(value='music', path=Fields('baz'), context=DatumInContext(value={'baz': 'music'}, path=<jsonpath_rw.jsonpath.Index object at 0x025CA770>, context=DatumInContext(value=[{'baz': 'news'}, {'baz': 'music'}], path=Fields('foo'), context=DatumInContext(value={'foo': [{'baz': 'news'}, {'baz': 'music'}]}, path=This(), context=None))))]
2.獲取匹配的資料match.value
jsonpath_expr = parse('foo[*].baz')
data = {'foo': [{'baz': 'news'}, {'baz': 'music'}]}
print([match.value for match in jsonpath_expr.find(data)])執行結果:['news', 'music']
3.match.value返回資料是一個list,我們要獲取特定的值
jsonpath_expr = parse('foo[*].baz') data = {'foo': [{'baz': 'news'}, {'baz': 'music'}]} print([match.value for match in jsonpath_expr.find(data)][0]) 執行結果: news