组合jsonpath查询以返回过滤数组的第一个对象有问题。

22

使用ashphy json path evaluator,以及以下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
      },
      { "category": "fiction",
        "author": "Herman Melville",
        "title": "Moby Dick",
        "isbn": "0-553-21311-3",
        "price": 8.99
      },
      { "category": "fiction",
        "author": "J. R. R. Tolkien",
        "title": "The Lord of the Rings",
        "isbn": "0-395-19395-8",
        "price": 22.99
      }
    ],
    "bicycle": {
      "color": "red",
      "price": 19.95
    }
  }
}

我希望编写一个过滤类别(例如:“小说”)并仅返回第一个元素的查询。但我好像无法弄清楚。

例如,$..book[?(@.category == "fiction")]将返回3本书的数组,但我只想要第一本书:

{ "category": "fiction",
        "author": "Evelyn Waugh",
        "title": "Sword of Honour",
        "price": 12.99
      }

能做到吗?明显的方法似乎是在末尾添加"[0]",但这样并不起作用。

1个回答

1
我查看了分析网站(注:这是来自测试 http://ashphy.com/JSONPathOnlineEvaluator/ 的信息):

enter image description here

放置 [0] 索引查找是有效的。该网站仅接受将放置在 jsonPath(jsonObj, query string) 参数内的内容,因此索引引用必须放在此评估之外,而该网站并未执行此操作。
jsonPath(foo, '$..book[?(@.category == "fiction")]')[0]

2
谢谢,但这不是我要找的——jsonPath返回一个数组,[0]访问数组的第一个元素。我需要jsonPath来过滤一个元素。我没有直接访问数组的权限。 - Blazes

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接