如何在JSONPath中按字符串过滤?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12585968/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:33:19  来源:igfitidea点击:

How to filter by string in JSONPath?

jsonjsonpath

提问by Alastair

I have a JSON response from the Facebook API that looks like this:

我有一个来自 Facebook API 的 JSON 响应,如下所示:

{
  "data": [
     {
       "name": "Barack Obama", 
       "category": "Politician", 
       "id": "6815841748"
     }, 
     {
       "name": "Barack Obama's Dead Fly", 
       "category": "Public figure", 
       "id": "92943557739"
     }]
 }

I want to apply JSONPath to it to only return results with a category of "Politician". From what I've read, it appears that I need to do:

我想对它应用 JSONPath 以仅返回具有“家”类别的结果。从我读过的内容来看,我似乎需要做:

$.data[?(@.category=='Politician')]

but according to the testing toolI found, this doesn't work. I found another questionwhich suggests that I should use "eq" instead of "==", but that doesn't work either. What am I getting wrong here?

但是根据我找到的测试工具,这不起作用。我发现了另一个问题,它表明我应该使用“eq”而不是“==”,但这也不起作用。我在这里出了什么问题?

采纳答案by pb2q

Your query looks fine, and your data and query work for me using this JsonPathparser. Also see the example queries on that page for more predicate examples.

您的查询看起来不错,您的数据和查询使用此 JsonPath解析器对我有用。另请参阅该页面上的示例查询以获取更多谓词示例。

The testing tool that you're using seems faulty. Even the examples from the JsonPath siteare returning incorrect results:

您使用的测试工具似乎有问题。甚至来自JsonPath 站点的示例也返回不正确的结果:

e.g., given:

例如,给定:

{
    "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
        }
    }
}

And the expression: $.store.book[?(@.length-1)].title, the tool returns a list of alltitles.

表达式:$.store.book[?(@.length-1)].title,该工具返回所有标题的列表。

回答by durandal

Drop the quotes:

去掉引号:

List<Object> bugs = JsonPath.read(githubIssues, "$..labels[?(@.name==bug)]");

See also this Json Path Example page

另请参阅此Json 路径示例页面

回答by Joe Meree

I didn't find find the correct jsonpath filter syntax to extract a value from a name-value pair in json.

我没有找到正确的 jsonpath 过滤器语法来从 json 中的名称-值对中提取一个值。

Here's the syntax and an abbreviated sample twitter document below.

下面是语法和简短的示例 twitter 文档。

This sitewas useful for testing:

该站点对测试很有用:

The jsonpath filter expression:

jsonpath 过滤器表达式:

.events[0].attributes[?(@.name=='screen_name')].value

Test document:

测试文档:

{
  "title" : "test twitter",
  "priority" : 5,
  "events" : [ {
    "eventId" : "150d3939-1bc4-4bcb-8f88-6153053a2c3e",
    "eventDate" : "2015-03-27T09:07:48-0500",
    "publisher" : "twitter",
    "type" : "tweet",
    "attributes" : [ {
      "name" : "filter_level",
      "value" : "low"
    }, {
      "name" : "screen_name",
      "value" : "_ziadin"
    }, {
      "name" : "followers_count",
      "value" : "406"
    } ]
  } ]
}

回答by Jeremy Deane

The browser testing tools while convenient can be a bit deceiving. Consider:

浏览器测试工具虽然方便,但可能有点欺骗性。考虑:

{
  "resourceType": "Encounter",
  "id": "EMR56788",
  "text": {
    "status": "generated",
    "div": "Patient admitted with chest pains</div>"
  },
  "status": "in-progress",
  "class": "inpatient",
  "patient": {
    "reference": "Patient/P12345",
    "display": "Roy Batty"
  }
}

Most tools returned this as false:

大多数工具将其返回为 false:

$[?(@.class==inpatient)]

But when I executed against

但是当我执行反对

<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
    <version>1.2.0</version>
</dependency>

It returned true. I recommend writing a simple unit test to verify rather than rely on the browser testing tools.

它返回true。我建议编写一个简单的单元测试来验证而不是依赖浏览器测试工具。

回答by Hakan Bilgin

''Alastair, you can use this lib and tool; DefiantJS. It enables XPath queries on JSON structures and you can test and validate this XPath:

''Alastair,你可以使用这个库和工具;DefiantJS。它启用对 JSON 结构的 XPath 查询,您可以测试和验证此 XPath:

//data[category="Politician"]

DefiantJS extends the global object with the method "search", which in turn returns an array with the matches. In Javascript, it'll look like this:

DefiantJS 使用“search”方法扩展全局对象,然后返回一个包含匹配的数组。在 Javascript 中,它看起来像这样:

var person = JSON.search(json_data, "//people[category='Politician']");
console.log( person[0].name );
// Barack Obama