How to filter a non-array in JsonPath

你离开我真会死。 提交于 2019-12-12 17:10:01

问题


Using the following JSON (from http://jsonpath.com):

{
  "firstName": "John",
  "lastName" : "doe",
  "age"      : 26,
  "address"  : {
    "streetAddress": "naist street",
    "city"         : "Nara",
    "postalCode"   : "630-0192"
  },
  "phoneNumbers": [
    {
      "type"  : "iPhone",
      "number": "0123-4567-8888"
    },
    {
      "type"  : "home",
      "number": "0123-4567-8910"
    }
  ]
}

I would like to get the root object only if firstName is John.

I have tried these inputs and many other similar ones:

  • $.[?($.firstName == 'John')]
  • $.[?($.'firstName' == 'John')]
  • $.[?(@.firstName == 'John')]
  • $[?($.firstName == "John")]

It seems as though filtering is only intended for arrays so this is an unsupported function. Does someone know a way to do this in Json.NET, or confirm that it's not possible and maybe point me to a library which supports the above?

I'm using F# but that's not important because F# is compatible with C#, .NET and NuGet packages.


回答1:


JSON path is intended to locate data in a JSON object and not to perform some processing or testing on that data. The filter notation is used to identify an item in an array with the purpose of returning that data or some part of it. Having objects in an array means that there may be many properties with the same name that have to be filtered by some other means in order to select a subset of them.
Using filter notation on an object property is not the same thing. There can only be one property in an object with a particular name so stating that name is sufficient to identify it uniquely. You can easily achieve the effect you require by getting $.firstName and then testing separately for the value "John"



来源:https://stackoverflow.com/questions/43707780/how-to-filter-a-non-array-in-jsonpath

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!