Json.NET JSONPath query not returning expected results

前端 未结 1 1857
悲&欢浪女
悲&欢浪女 2020-12-06 19:29

I\'m using Newtonsoft\'s Json.Net to select nodes from the following json:

{  
   \"projects\":[  
      {  
         \"name\":\"Project 1\",
         \"clie         


        
相关标签:
1条回答
  • 2020-12-06 20:30

    Json.NET's JSONPath parser allows the filter (script) expression [?( )] to query for nested properties inside child objects of the candidate array item(s). Thus

    var test = json.SelectTokens(@"$.projects[?(@.client.code == 'DEF')].client");
    

    returns, as desired,

    [
      {
        "code": "DEF",
        "name": "Client 2"
      }
    ]
    

    Working .Net fiddle.

    Upon experimentation it seems none of the JSONPath implementations at jsonpath.curiousconcept.com support this syntax, however it works correctly at jsonpath.com which uses https://github.com/ashphy/jsonpath-online-evaluator. The JSONPath proposal simply states that () is a script expression, using the underlying script engine which clearly leaves some room for interpretation as to whether and how this "should" work.

    The filters used in the question apparently do not work with Json.NET because, as of version 10.0.3, it only officially supports applying filters to array items and not directly to objects -- see Issue #1256: JSONPath scripts not executing correctly for objects for a discussion. (Though sometimes cunning workarounds can be found, for instance in this answer.) Using nested properties inside filters, however, seems to be intended to work (and does work).

    0 讨论(0)
提交回复
热议问题