You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用libopenapi通过JSONPath按子节点条件定位OpenAPI根节点?

OpenAPI Overlay 根节点定位的JSONPath正确写法

你遇到的问题是RFC9535标准的JSONPath不支持嵌套过滤表达式(也就是你之前用的@['x-oai-traits'][?(@ == 'something')]写法),要检查数组是否包含指定元素,需要用标准内置的contains()函数。

可行的JSONPath表达式

直接用contains函数判断根节点的x-oai-traits数组是否包含something:

$[?contains(@['x-oai-traits'], 'something')]

因为x-oai-traits字段包含连字符,用@['x-oai-traits']的索引方式比@.x-oai-traits更稳妥,能避免解析歧义。

修改后的测试代码

将Overlay里的target表达式替换为上述写法即可:

package main

import (
    "fmt"

    "github.com/pb33f/libopenapi"
)

func main() {
    openApiDocumentText := `openapi: 3.1.0
info:
  title: API with a paged collection
  version: 1.0.0
x-oai-traits: ['something']
paths:
  /items:
    get:
      responses:
        200:
          description: OK
`

    overlayDocumentText := `overlay: 1.1.0
info:
  title: example overlay
  version: 1.0.0
actions:
  - target: "$[?contains(@['x-oai-traits'], 'something')]"
    update:
      info:
        license:
          name: Apache 2.0
          identifier: Apache-2.0
        `

    overlayResult, err := libopenapi.ApplyOverlayFromBytesToSpecBytes([]byte(openApiDocumentText), []byte(overlayDocumentText))
    if err != nil {
        panic(err)
    }

    for _, warning := range overlayResult.Warnings {
        fmt.Printf("Warning: %s (target: %s)\n", warning.Message, warning.Target)
    }

    fmt.Printf(string(overlayResult.Bytes))
}

运行这段代码后,OpenAPI文档的info节点会成功添加license字段,说明根节点已被正确匹配。

内容的提问来源于stack exchange,提问作者zelite

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.02 02:33:11