Skip to content

Add JsonPath support to JsonDocument/JsonElement #31068

Open

Description

@gary-holland

Hi,

I'd like to request JsonPath support for querying the JsonDocument/JsonElement classes. JsonPath provides similar capability to XPath (and even Sql) in that it allows queries to be performed against Json documents. This currently represents a major gap for us shifting from Newtonsoft to system.text.json, as we provide JsonPath values as an input parameter to a data load process which can't be worked around via code.

The JsonPath syntax is described here.

The equivalent functionality in the Newtonsoft library is:

var jsonPath = "$.my.path";
var json = JToken.Parse(jsonString);
var token = json.SelectToken(jsonPath);

The following proposed syntax would work well in the JsonDocument structure:

var jsonPath = "$.my.path";
var jsonDoc = JsonDocument.Parse(json);
var element = jsonDoc.SelectElement(jsonPath); //returns JsonElement
var elements = jsonDoc.SelectElements(jsonPath); //returns JsonElement.ArrayEnumerator

Thanks.

Activity

  1. dazinator commented on Oct 23, 2019

    @dazinator

    Just searched for a similar thing myself. The appropriate newtonsoft documentation for this: https://www.newtonsoft.com/json/help/html/QueryJsonSelectTokenJsonPath.htm

  2. dkmiller commented on Nov 20, 2019

    @dkmiller

    Seconding this. It would be extremely useful.

  3. NickMSW commented on Dec 13, 2019

    @NickMSW

    Would also like to push this up the stack. We want to use system.text.json but the lack of JsonPath is blocking us.

  4. transferred this issue fromdotnet/corefxon Feb 1, 2020
  5. added this to the Future milestone on Feb 1, 2020
  6. azambrano commented on Mar 31, 2020

    @azambrano

    In the meantime. I'm doing some experiment following the same strategy of the Json.net for support JsonPath but using System.Text.Json.JsonDocument https://github.com/azambrano/JsonDocumentPath

  7. NinoFloris commented on Apr 13, 2020

    @NinoFloris
    Contributor

    @layomia did this and writedom move out of scope for 5.0?

  8. zmhh commented on May 28, 2020

    @zmhh

    If this is implemented it would be nice to have the option for case insensitivity.

  9. Laiteux commented on May 29, 2020

    @Laiteux

    We want this

  10. onionhammer commented on Jun 5, 2020

    @onionhammer

    This would be very useful

  11. blushingpenguin commented on Jun 8, 2020

    @blushingpenguin
  12. blushingpenguin commented on Jun 8, 2020

    @blushingpenguin

    It's pretty similar (it's also a port of Newtonsoft.Json's implementation), but is missing some of the functionality of the original and lacks a nuget package. (AFAIK I've ported all of the original functionality).

    I could have forked that one, but my version is actually a port of https://github.com/blushingpenguin/MongoDB.Bson.Path (which is a version that works on the MongoDB.BsonDocument family).

  13. gregsdennis commented on Oct 12, 2020

    @gregsdennis
    Contributor

    More support for JSON Path

  14. GF-Huang commented on Nov 19, 2020

    @GF-Huang

    Does it merged into .NET 5?

  15. 36 remaining items

  16. ay-azara commented on Mar 29, 2024

    @ay-azara

    Instead of a complex query mechanism could we get a JSON flatten function so we can deserialize to a Dictionary<string, string> and perform the "lookup" on the key?

    {
        "foo": {
            "bar": "baz"
        }
    }
    {
        "foo.bar":  "baz"
    }
    // Something like
    var dict = json.Deserialize<Dictionary<string, string>>(JsonSerializer.Flatten(json))
    var val = dict['foo.bar']
  17. peteraritchie commented on Mar 29, 2024

    @peteraritchie
    var val = dict['foo.bar']
    

    That's getting really close to being a JSONPath expression, there's just an implied $. at the start of foo.bar. With the notation you're proposing, how would you support collections and arrays? i.e. one way to support that is to use JSONPath notation. :)

  18. gregsdennis commented on Mar 29, 2024

    @gregsdennis
    Contributor

    If you want a single value, you don't want JSON Path. You want JSON Pointer: /foo/bar. I have an implementation of that, too.

  19. ay-azara commented on Mar 29, 2024

    @ay-azara
    var val = dict['foo.bar']
    

    That's getting really close to being a JSONPath expression, there's just an implied $. at the start of foo.bar. With the notation you're proposing, how would you support collections and arrays? i.e. one way to support that is to use JSONPath notation. :)

    It would be the index of the array/collection object. foo.bar.0.baz

    Just to clarify, when I said "instead" it was meant as a short term compromise, not "you all should give up on JSON Path support". From my perspective, the issue has been open since 2019 so I can only assume that implementing JSON Path is a bigger ask than a flattening function. I'm willing to settle for a less rigorous but still workable solution in the short term rather than a perfect solution that may never get implemented. It's fine if you don't want to settle, my use case is not as stringent as yours probably is.

    And I think Greg's json-everything is wonderful but for some orgs it's easier to use a library that has already been cleared for use.

    Based on the flurry of downvotes I see it's not something worth pushing further.

  20. gregsdennis commented on Mar 31, 2024

    @gregsdennis
    Contributor

    @ay-azara to get you by, here's an extension that builds an index keyed by JSON Pointers:

    public static Dictionary<string, JsonNode?> Index(this JsonNode? node)
    {
        var index = new Dictionary<string, JsonNode?>();
        var search = new Queue<(string Pointer, JsonNode? Value)>();
        search.Enqueue((string.Empty, node));
    
        while (search.Any())
        {
            var current = search.Dequeue();
            index[current.Pointer] = current.Value;
            switch (current.Value)
            {
                case JsonObject obj:
                    index[current.Pointer] = obj;
                    foreach (var kvp in obj)
                    {
                        search.Enqueue(($"{current.Pointer}/{Encode(kvp.Key)}", kvp.Value));
                    }
                    break;
                case JsonArray arr:
                    index[current.Pointer] = arr;
                    for (var i = 0; i < arr.Count; i++)
                    {
                        var value = arr[i];
                        search.Enqueue(($"{current.Pointer}/{i}", value));
                    }
    
                    break;
            }
        }
    
        return index;
    }
    
    private static string Encode(string value)
    {
        if (value.All(c => c is not ('~' or '/'))) return value;
    
        var builder = new StringBuilder();
        foreach (var ch in value)
        {
            switch (ch)
            {
                case '~':
                    builder.Append("~0");
                    break;
                case '/':
                    builder.Append("~1");
                    break;
                default:
                    builder.Append(ch);
                    break;
            }
        }
    
        return builder.ToString();
    }

    Again, pointers are ideal since each entry only identifies a single location.

  21. ay-azara commented on Apr 1, 2024

    @ay-azara

    @gregsdennis Thanks man, appreciate you taking the time :)

  22. isaevdan commented on Nov 25, 2024

    @isaevdan

    Any updates when this will be available? The issue is from 2019
    BTW Newtonsoft.Json has bugs in their implementation

  23. gregsdennis commented on Nov 25, 2024

    @gregsdennis
    Contributor

    @isaevdan as mentioned in a comment above, you can use JsonPath.Net if you need something now.

  24. isaevdan commented on Nov 25, 2024

    @isaevdan

    @isaevdan as mentioned in a comment above, you can use JsonPath.Net if you need something now.

    Yep, thanks and appreciate you work
    Just in progress in migrating to JsonPath.NET, but still weird it's not part of library :)

  25. isaevdan commented on Nov 25, 2024

    @isaevdan

    Created JsonExtensions - wrapper with couple of same methods as from NewtonsoftJson but with provided libraries, may be a good starting point for others who are going to do migration

    public static class JsonExtensions
    {
        public static JsonNode SelectToken(this JsonNode node, string path,
            PathEvaluationOptions options = null)
        {
            var jsonPath = JsonPath.Parse(path);
            var matches = jsonPath.Evaluate(node, options).Matches;
            if (matches.Count > 1)
                throw new JsonException("Path returned multiple tokens.");
            return matches.FirstOrDefault()?.Value;
        }
    
        public static List<JsonNode> SelectTokens(this JsonNode node, string path,
            PathEvaluationOptions options = null)
        {
            var jsonPath = JsonPath.Parse(path);
            return
                jsonPath.Evaluate(node, options)
                    .Matches
                    .Select(m => m.Value)
                    .ToList();
        }
    
        public static IList<JsonNode> Children(this JsonNode node)
        {
            return node switch
            {
                JsonArray array => array.ToList(),
                JsonObject obj => obj.Select(e => e.Value).ToList(),
                _ => []
            };
        }
    
        public static JsonNode? ParseJsonNode(string text)
        {
            // Handle empty or null input text
            if (string.IsNullOrWhiteSpace(text))
            {
                return null;
            }
    
            try
            {
                return JsonNode.Parse(text);
            }
            catch (JsonException)
            {
                return null;
            }
        }
    }
    
  26. FransVanEk commented on Oct 8, 2026

    @FransVanEk

    For anyone who needs JSONPath on System.Text.Json today, and as input for a possible built-in API: I've published TLio.JsonPath 1.1, a stable, MIT-licensed JSONPath engine for JsonNode with no dependencies. It runs on .NET 8 and later.

    using System.Text.Json.Nodes;
    using TLio.JsonPath;
    
    var engine = new JsonPathEngine(new JsonPathOptions { Dialect = JsonPathDialect.Rfc9535 });
    
    foreach (var match in engine.Select("$.store.book[[email protected] < 10].title", doc))
        Console.WriteLine($"{match.NormalizedPath} = {match.Node}");
    
    // Newtonsoft SelectToken equivalent (more than one match throws)
    JsonPathMatch? one = engine.SelectSingle("$.store.book[0].title", doc);

    Some findings from building it that are relevant to the API design here:

    1. Newtonsoft's JSONPath and RFC 9535 can't be one rule set. They differ in syntax ($.a-b, [?(...)] vs [?...]), in results ($..*, filters over objects, != on a missing member) and in error behaviour. A migration path from SelectToken and a standards-based API pull in different directions, so a built-in API would need to choose explicitly. The package solves this with a dialect option set once per engine:
      • Newtonsoft matches SelectToken(s) in Newtonsoft.Json 13.0.4, verified with differential tests against Newtonsoft itself.
      • Rfc9535 passes all 706 tests of the JSONPath Compliance Test Suite, including function extensions and I-Regexp (RFC 9485).
      • Extended is a superset of both.
    2. JSON null versus a missing value. JsonNode represents JSON null as a C# null, so a match result needs Parent plus Name or Index to tell {"a": null} apart from {} for $.a.
    3. Safety limits. A regex timeout, a maximum query length and a maximum depth are needed so that hostile input fails with an error instead of a stack overflow or runaway regex.
    4. Parse once, evaluate many. An immutable, thread-safe parsed query with a per-engine cache, and syntax errors that report the character position at parse time.

    Scope: it works on the mutable JsonNode DOM, so matches are live nodes you can read, replace or remove. A read-only JsonElement variant is possible but not built yet; today a JsonElement can be queried after JsonObject.Create(element), at the cost of a copy.

    If the team decides to move this issue forward, I'm happy to help write an API proposal, and to contribute the test corpus, including the dialect-divergence cases, for an implementation.

    Source: https://github.com/SQUORA-NL/TLio/tree/main/TLio.JsonPath

  27. ghadzhigeorgiev commented on Oct 8, 2026

    @ghadzhigeorgiev

    Great effort @FransVanEk!

    There are other 3rd party libs, like Meziantou.Framework.JsonPath

    The point is to have it natively, and that now takes 7 years :(

  28. FransVanEk commented on Oct 8, 2026

    @FransVanEk

    Great effort @FransVanEk!

    There are other 3rd party libs, like Meziantou.Framework.JsonPath

    The point is to have it natively, and that now takes 7 years :(

    Thanks, I hadn't come across this repo. Yet, I had very specific requirements: it needed to mimic the same behavior as the Newtonsoft version.

    I know the intent was to have it natively. I don't have much hope, but I won't give up hoping nonetheless...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-suggestionarea-System.Text.Jsonpartner-impact

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions