JamesNK / Newtonsoft.Json

Json.NET is a popular high-performance JSON framework for .NET
https://www.newtonsoft.com/json
MIT License
10.71k stars 3.24k forks source link

array.length jsonpath for the selectToken method returned null instead of count #2916

Open Rahna-S opened 9 months ago

Rahna-S commented 9 months ago

"arrayobject.length" jsonpath for the method selecttoken returned null instead of numerical value.

Expected behavior

It should return the array count.

Actual behavior

Returned null.

Steps to reproduce


// Your calls to Newtonsoft.Json here
string jsonExpressionText = "$.attachment.length";
JToken token = jsonObject.SelectToken(jsonExpressionText);

Here, attachment is an array and the expression returns null.
elgonzo commented 9 months ago

I am only a user of Newtonsoft.Json and not otherwise associated with the project or its author/maintainer. That said, i would strongly suggest you ponder a possible migration from Newtonsoft.Json to System.Text.Json if JsonPath support is important to you. While JsonPath support in System.Text.Json itself is lacking as of now, there is the (in my opinion) excellent JsonPath.Net library (doc, github), which not only is substantially better than Newtonsoft.Json's JsonPath support (striving to support the current JsonPath specification), but it also is actively maintained. Plus, there is a handy JsonPath.Net-based online evaluator for quickly trying out and messing about with JsonPath expressions (https://json-everything.net/json-path/). However, JsonPath.Net relies on STJ and can't be used on top of Newtonsoft.Json.

If you don't want or cannot migrate to STJ, then i guess you unfortunately will be stuck with Newtonsoft.Json's quirky and outdated JsonPath implementation. Support for the length function (and other functions in JsonPath) has been asked for years ago (see this open ticket, for example: https://github.com/JamesNK/Newtonsoft.Json/issues/1318), and in my frank opinion i would see it as a small miracle if Newtonsoft.Json were to receive noteworthy feature updates anymore. (Personally, i consider Newtonsoft.Json a largely feature-frozen legacy library, with System.Text.Json being the go-to for Json processing in .NET these days.)