根据JSONPATH中数组中的字符串过滤Json

use*_*561 2 jsonpath

我有一种情况,我有一个json String,它有一个子类作为只包含字符串的数组.是否可以获得包含特定String的数组的对象引用.例:

{ "Books":{  
      "History":[  
         {  
            "badge":"y",
            "Tags":[  
               "Indian","Culture"
            ],
            "ISBN":"xxxxxxx",
            "id":1,
            "name":"Cultures in India"
         },
         {  
            "badge":"y",
            "Tags":[  
               "Pre-historic","Creatures"
            ],
            "ISBN":"xxxxxxx",
            "id":1,
            "name":"Pre-historic Ages"
         }
     ]
  }
}
Run Code Online (Sandbox Code Playgroud)

要实现:从上面的JSON字符串中,需要获取历史记录中包含"tags"列表中"Indian"的所有书籍.

我在我的项目中使用JSONPATH但是如果有其他API可以提供类似的功能,欢迎任何帮助.

riy*_*iya 6

如果您使用的是 Goessner JSONPath,$.Books.History[?(@.Tags.indexOf('Indian') != -1)]正如上面Duncan 提到的那样应该可以工作。

如果您正在使用 Jayway Java 端口 (github.com/jayway/JsonPath),那么 $.Books.History[?(@.Tags[?(@ == 'Indian')] != [])]或更优雅地使用这样的in运算符$.Books.History[?('Indian' in @.Tags)]。在这里都试过了。

  • 对我来说 Tags[?(@ == 'Indian')] != null 有效(null 而不是 [])。如果有人觉得有用的话,我正在 C# 中使用 Newtonsoft.Json.Linq.JToken。 (2认同)

Dun*_*can 5

假设您使用的是Goessner JSONPath(http://goessner.net/articles/JsonPath/),则以下内容应该有效:

$.Books.History[?(@.Tags.indexOf('Indian') != -1)]
Run Code Online (Sandbox Code Playgroud)

根据Goessner站点,您可以在?()过滤器中使用底层JavaScript .因此,您可以使用JavaScript indexOf函数检查您的Tags数组是否包含"Indian"标签.

使用此JSONPath查询测试器查看此处的工作示例:http: //www.jsonquerytool.com/sample/jsonpathfilterbyarraycontents


小智 0

您尝试过使用 underscoreJS 吗?你可以像这样获得印度书籍:

var data = {"Books:"....};

var indianBooks = _.filter(data.Books.History, function(book) { return _.contains(book.Tags, "Indian"); })
Run Code Online (Sandbox Code Playgroud)