Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter a non-array in JsonPath

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.

like image 424
matt_rule Avatar asked Apr 30 '17 14:04

matt_rule


People also ask

Can you use wildcards in JSON?

You can only perform wildcard matches against JSON properties with text (string) values. Numbers, booleans, nulls are indexed separately in JSON. For details, see Creating Indexes and Lexicons Over JSON Documents in the Application Developer's Guide.

What is a JSON path expression?

JSONPath is a query language for JSON, similar to XPath for XML. It allows you to select and extract data from a JSON document. You use a JSONPath expression to traverse the path to an element in the JSON structure.

What is JSONPath used for?

JSONPath is a query language for JSON with features similar to XPath for XML. JSONPath is used for selecting and extracting a sub-section from the JSON document.


1 Answers

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"

like image 110
Andy Bisson Avatar answered Sep 28 '22 07:09

Andy Bisson