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

时间:2015-05-04 12:51:23

标签: 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"
         }
     ]
  }
}

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

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

3 个答案:

答案 0 :(得分:5)

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

$.Books.History[?(@.Tags.indexOf('Indian') != -1)]

根据Goessner网站,您可以在?()过滤器中使用基础JavaScript。因此,您可以使用JavaScript indexOf函数检查您的Tags数组是否包含“' Indian'

”标签。

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

答案 1 :(得分:1)

如果您使用的是Goessner JSONPath,则应该使用Duncan above提到的$.Books.History[?(@.Tags.indexOf('Indian') != -1)]

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

答案 2 :(得分:0)

您是否尝试使用underscoreJS?你可以得到这样的印度书籍:

     XmlSerializer xmlSerSale = new XmlSerializer(typeof(UserInfo));

                        StringReader stringReader = new StringReader(myXML);

                        info = (UserInfo)xmlSerSale.Deserialize(stringReader);

                        stringReader.Close();
相关问题