Python关于jsonpath路径里面包含中文或进行参数化的解决方案

发布时间 2023-04-28 10:20:16作者: 六六家的小弟

jsonpath路径包含中文

当jsonpath路径包含中文时,我们只需要在jsonpath路径里面把中文用引号包裹即可
准备json文件

{
    "data": [
        {
            "Details": [
                {
                    "姓名": "张三"
                }
            ]
        }
    ]
}
                    
jsonpath :"$.data[0].Details[0].'姓名'"

json方法

    def get_value_from_json(self, resp, jsonpath):
        jsonexpr = parse(jsonpath)
        try:
            return [match.value for match in jsonexpr.find(resp)]
        except IndexError as e:
        return "匹配出错"

结果

jsonpath路径包含参数

解决方法也是一样的,我们只需要把参数用引号包裹即可

key='姓名'
jsonpath:f"$.data[0].Details[0].'{key}'"

其结果也是一样的