首页 > 解决方案 > 如何使用 JsonPath 按字符串过滤后反映结果的整个 json

问题描述

我可以使用 JsonPath 按字符串过滤后反映结果的整个 json 吗?

{
    "store": {
        "book": [
            {
                "category": "reference",
                "author": "Nigel Rees",
                "title": "Sayings of the Century",
                "price": 8.95
            },
            {
                "category": "fiction",
                "author": "Evelyn Waugh",
                "title": "Sword of Honour",
                "price": 12.99
            } 
        ],
        "bicycle": {
            "color": "red",
            "price": 19.95
        }
    },
    "expensive": 10
}

{
    "store": {
        "book": [
            {
                "category": "reference",
                "author": "Nigel Rees",
                "title": "Sayings of the Century",
                "price": 8.95
            }       
        ],
        "bicycle": {
            "color": "red",
            "price": 19.95
        }
    },
    "expensive": 10
}

按字符串过滤书是通过 '$..book[?(@.author =~ /.*REES/i)]'

但是你能告诉我让整个 JSON 得到反映吗?

标签: jsonjsonpathjayway

解决方案


您不能使用 JSONPath 执行此操作;虽然您想根据内部项目属性选择最外面的项目,但您不想整体检索外部项目。那是行不通的。

选择外部项目可以这样完成

$..store[?(@.book[0].author =~ /.*REES/i)]

但这也将返回位置 2 的书,即索引 1。

听起来您实际上需要像Jolt这样的 JSON 转换。

例如,Jolt 的删除转换器将允许您像这样删除第二本书:

[
  {
    "operation": "remove",
    "spec": {
      "store": {
        "book": {
          "array": {
            "1": "" //remove book at position 2
          }
        }
      }
    }
  }
]

在此处使用您自己的输入在线尝试。


推荐阅读