You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Add JsonPath support to JsonDocument/JsonElement #31068
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.
Reacted by Darrell, John Youngers, Dan Miller, LeaFrock, Ryan Harvey, Andrew Omondi, Vladimir Bukreev, Andrew Colombi, Kyle Gobel, marcogomex and 323 more
Reacted by Manoj Baishya, Weihan Li, Constante-ou-Mort, Mrxx99, Markus Schlotbohm, ghadzhigeorgiev, Leo Lee and Erwin
Reacted by Mark Laureta, Sergey Frolov, Rafael Mac Menz, André de Jager, Mark Sutyak, Roland Kölbel, Manoj Baishya, ksemenenko, gparmigiani, Constante-ou-Mort and 4 more
Reacted by Evgeniy Alexandrov, Mrxx99, Markus Schlotbohm, Leo Lee and Erwin
Reacted by Mad Max, WorldIsM, hell-racer, Fernando Velloso Borges de Mélo Gomes, suchoss, Cuneytt, Philippe Vlérick, Conor Lawton, Manoj Baishya, gorillapower and 12 more
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).
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?
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. :)
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.
@ay-azara to get you by, here's an extension that builds an index keyed by JSON Pointers:
publicstaticDictionary<string,JsonNode?>Index(thisJsonNode?node){varindex=newDictionary<string,JsonNode?>();varsearch=newQueue<(stringPointer,JsonNode?Value)>();search.Enqueue((string.Empty,node));while(search.Any()){varcurrent=search.Dequeue();index[current.Pointer]=current.Value;switch(current.Value){caseJsonObjectobj:index[current.Pointer]=obj;foreach(varkvpinobj){search.Enqueue(($"{current.Pointer}/{Encode(kvp.Key)}",kvp.Value));}break;caseJsonArrayarr:index[current.Pointer]=arr;for(vari=0;i<arr.Count;i++){varvalue=arr[i];search.Enqueue(($"{current.Pointer}/{i}",value));}break;}}returnindex;}privatestaticstringEncode(stringvalue){if(value.All(c =>cis not ('~' or '/')))returnvalue;varbuilder=newStringBuilder();foreach(varchinvalue){switch(ch){case'~':builder.Append("~0");break;case'/':builder.Append("~1");break;default:builder.Append(ch);break;}}returnbuilder.ToString();}
Again, pointers are ideal since each entry only identifies a single location.
Reacted by ay-azara, Pascal van Buijtene and Liam Gingrich
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;
}
}
}
Reacted by ay-azara, Frank R. Haugen, Brycen G, John Iwasz and Meir Blachman
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.
usingSystem.Text.Json.Nodes;usingTLio.JsonPath;varengine=newJsonPathEngine(newJsonPathOptions{Dialect=JsonPathDialect.Rfc9535});foreach(varmatchinengine.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:
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.
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.
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.
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.
Activity
dazinator commentedon Oct 23, 2019
Just searched for a similar thing myself. The appropriate newtonsoft documentation for this: https://www.newtonsoft.com/json/help/html/QueryJsonSelectTokenJsonPath.htm
dkmiller commentedon Nov 20, 2019
Seconding this. It would be extremely useful.
NickMSW commentedon Dec 13, 2019
Would also like to push this up the stack. We want to use system.text.json but the lack of JsonPath is blocking us.
azambrano commentedon Mar 31, 2020
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
NinoFloris commentedon Apr 13, 2020
@layomia did this and writedom move out of scope for 5.0?
zmhh commentedon May 28, 2020
If this is implemented it would be nice to have the option for case insensitivity.
Laiteux commentedon May 29, 2020
We want this
onionhammer commentedon Jun 5, 2020
This would be very useful
blushingpenguin commentedon Jun 8, 2020
I've ported the Newtonsoft.Json implementation to work with JsonDocument, along with the tests.
nuget: https://www.nuget.org/packages/BlushingPenguin.JsonPath/
source: https://github.com/blushingpenguin/BlushingPenguin.JsonPath/
Laiteux commentedon Jun 8, 2020
Hello, what's the difference with this? https://github.com/azambrano/JsonDocumentPath
blushingpenguin commentedon Jun 8, 2020
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).
gregsdennis commentedon Oct 12, 2020
More support for JSON Path
GF-Huang commentedon Nov 19, 2020
Does it merged into
.NET 5?36 remaining items
ay-azara commentedon Mar 29, 2024
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" }peteraritchie commentedon Mar 29, 2024
That's getting really close to being a JSONPath expression, there's just an implied
$.at the start offoo.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. :)gregsdennis commentedon Mar 29, 2024
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.ay-azara commentedon Mar 29, 2024
It would be the index of the array/collection object.
foo.bar.0.bazJust 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.
gregsdennis commentedon Mar 31, 2024
@ay-azara to get you by, here's an extension that builds an index keyed by JSON Pointers:
Again, pointers are ideal since each entry only identifies a single location.
ay-azara commentedon Apr 1, 2024
@gregsdennis Thanks man, appreciate you taking the time :)
isaevdan commentedon Nov 25, 2024
Any updates when this will be available? The issue is from 2019
BTW Newtonsoft.Json has bugs in their implementation
gregsdennis commentedon Nov 25, 2024
@isaevdan as mentioned in a comment above, you can use JsonPath.Net if you need something now.
isaevdan commentedon Nov 25, 2024
Yep, thanks and appreciate you work
Just in progress in migrating to JsonPath.NET, but still weird it's not part of library :)
isaevdan commentedon Nov 25, 2024
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
Meir017 commentedon Apr 29, 2025
https://github.com/json-everything/json-everything/tree/master/src/JsonPath can be used, and their docs https://docs.json-everything.net/path/basics/
FransVanEk commentedon Oct 8, 2026
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
JsonNodewith no dependencies. It runs on .NET 8 and later.Some findings from building it that are relevant to the API design here:
$.a-b,[?(...)]vs[?...]), in results ($..*, filters over objects,!=on a missing member) and in error behaviour. A migration path fromSelectTokenand 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:NewtonsoftmatchesSelectToken(s)in Newtonsoft.Json 13.0.4, verified with differential tests against Newtonsoft itself.Rfc9535passes all 706 tests of the JSONPath Compliance Test Suite, including function extensions and I-Regexp (RFC 9485).Extendedis a superset of both.JsonNoderepresents JSON null as a C#null, so a match result needsParentplusNameorIndexto tell{"a": null}apart from{}for$.a.Scope: it works on the mutable
JsonNodeDOM, so matches are live nodes you can read, replace or remove. A read-onlyJsonElementvariant is possible but not built yet; today aJsonElementcan be queried afterJsonObject.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
ghadzhigeorgiev commentedon Oct 8, 2026
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 :(
FransVanEk commentedon Oct 8, 2026
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...