Search code examples
jsonjson.netjsonpath

What is the JsonPath syntax used by Json.NET?


I'm trying to select some nodes with Json.NET SelectTokens it doesn't seem to support the same syntax the original jsonpath supports. Given this input:

{
    "a": [
        {
            "id": 1
        }
    ],
    "b": [
        {
            "id": 2
        },
        {
            "id": 3,
            "c": {
                "id": 4
            }
        }
    ],
    "d": [
        {
            "id": 5
        }
    ]
}

I want the ids of all top level objects inside aand b only, but not of inner objects. Using goessner's parser I'm able to do it with: $.[a,b].*.id, it returns [1, 2, 3].

Json.NET doesn't seem to support neither the comma or the *. How can this be achieved with Json.NET and are there any reference for what is supported by Json.NET jpath selectors?


Solution

  • The following path will work with Json.NET 10.0.2:

    var path = @"$.['a','b'][*].id";
    

    This path seems consistent with the original JsonPATH article, which states:

    JSONPath expressions can use the dot–notation

    $.store.book[0].title

    or the bracket–notation

    $['store']['book'][0]['title']

    Specifically:

    • Names inside brackets are shown to be quoted. Presumably doing so distinguishes between indices and numeric names.

    • Array indices are always shown to be in brackets rather than between periods.

    Sample fiddle.

    (Honestly, the original article is somewhat vague and allows for variation in implementation. For instance, exactly what does script expression, using the underlying script engine mean?)