skip to Main Content

Is there a way to get the last item of a JSON array using a JSON query only (in this case Newtonsoft.Json SelectToken method)?

I can not use the Last method from Newtonsoft.Json, as I get the query from a frontend textbox and the only one who knows about structure of the JSON document is the user themself. They may want to get last item of an array in some of their JSON queries.

If the only choice is to use this Last method, I would need to add an override of SelectToken which accepts queries with a negative index and split normal and minus queries and then run these split sections in Last or SelectToken methods which is not a good solution for me.

I tried multiple syntaxes with SelectToken but I got exceptions (embeded in comments):

var jsonArray = @"[{""Name"":""amir0"",""Id"":0},{""Name"":""amir1"",""Id"":1}]";
var array = JArray.Parse(jsonArray);
        
Console.WriteLine(array.SelectToken("[-1].Name")); //Unhandled exception. System.ArgumentOutOfRangeException: Index was out of range.
Console.WriteLine(array.SelectToken("[^1].Name")); //Unhandled exception. Newtonsoft.Json.JsonException: Unexpected character while parsing path indexer: ^

2

Answers


  1. If you look at the JSONPath documentation, there are two examples of how to get the last element with SelectToken, though only one of them is actually supported in Newtonsoft.Json (Issue):

    var jsonArray = @"[{""Name"":""amir0"",""Id"":0},{""Name"":""amir1"",""Id"":1}]";
    var array = JArray.Parse(jsonArray);
            
    Console.WriteLine(array.SelectToken("[-1:].Name"));
    Console.WriteLine(array.SelectToken("[(@.length-1)].Name")); //Valid syntax, but not supported
    

    In short, use [-1:] to get the last element.

    Login or Signup to reply.
  2. if you only want to get the last item from your JSON array maybe you can try this way

    var jsonArray = @"[{""Name"":""amir0"",""Id"":0},{""Name"":""amir1"",""Id"":1}]";
    var array = JArray.Parse(jsonArray);
    
    
    var lastItem = array[array.Count - 1];
    Console.WriteLine(lastItem["Name"]);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search