使用jsonpath-ng替换数组元素时结果不符合预期的问题
使用jsonpath-ng替换数组元素的正确写法
原始YAML结构
paths /api/v1/chats: get: - name: other_chats in: query required: false type: boolean - name: status in: query required: false allOf: - $ref: '#/definitions/ChatStatus'
期望输出结构
paths /api/v1/chats: get: - name: other_chats in: query required: false type: boolean - name: status in: query required: false type: string
尝试的两种写法及问题
第一种写法
all_of_expr = parse("$.paths.*.*.parameters[?(@.allOf)]") all_of_elements = all_of_expr.find(openapi) openapi = all_of_expr.update(openapi, {"type": "string"})
错误输出:
paths /api/v1/chats: get: - name: other_chats in: query required: false type: boolean - type: string
问题:匹配到整个参数元素后直接替换,覆盖了原有字段,导致参数的name、in等信息丢失。
第二种写法
all_of_expr = parse("$.paths.*.*.parameters[*].allOf") all_of_elements = all_of_expr.find(openapi) openapi = all_of_expr.update(openapi, {"type": "string"})
错误输出:
paths /api/v1/chats: get: - name: other_chats in: query required: false type: boolean - name: status in: query required: false allOf: type: string
问题:匹配的是allOf字段本身,仅替换了该字段的值,没有删除allOf并将type添加到参数节点下。
正确解决方法
需要先定位到包含allOf的参数元素,再修改该元素的内部属性,而非直接替换节点内容:
from jsonpath_ng import parse # 假设openapi是加载后的YAML字典对象 all_of_expr = parse("$.paths.*.*.parameters[?(@.allOf)]") matches = all_of_expr.find(openapi) for match in matches: # 获取匹配到的参数字典 param_dict = match.value # 删除allOf字段 del param_dict["allOf"] # 添加type字段 param_dict["type"] = "string"
这样处理后,目标参数会保留原有字段,同时删除allOf并添加type: string,符合预期输出。
内容的提问来源于stack exchange,提问作者p.magalhaes
相关产品推荐
相关产品推荐

