Home > Back-end >  Get last character from json
Get last character from json

Time:10-12

How to get last and last but one character in json file.

Tried,

jsonTxt .Substring(jsonTxt .Length - 1, jsonTxt .Length)

does not seem to work for fetching last character. Shows error as "Index and length must refer to a location within the string. (Parameter 'length')"

Json file:

As you could see below, json file mssing ']' bracket and has extra ',' at the end.

 [
   {"item":0,"d":"09/30/2022","h":0},
   {"item":1,"d":"09/30/2022","h":0},

Sample:

    jsonTxt .Substring(0, jsonTxt .Length - 3) 
    Above line trims comma and outputs Json as below
    [
      {"item":0,"d":"09/30/2022","h":0},
      {"item":1,"d":"09/30/2022","h":0}

Doubt is why it works for jsonText.substring(0, jsonText.Length-3), whereas I expect the syntax to jsonText.substring(0, jsonText.Length-1). As it is the last character in file.

Razor code:

 var utf8Json = _loadedFile.OpenReadStream(maxAllowedSize: 1024 * 1024 * 10); 
 using var reader = new StreamReader(utf8Json);
 string jsonTxt = await reader.ReadToEndAsync();

 @* below line fetches string until the end excluding last ',' *@
 string jsonText = jsonTxt .Substring(0, jsonTxt .Length - 3);

 @* below line appends ']' to the json file
 var jsonDocument = JsonDocument.Parse(jsonText   ']');

For the above code, I want to add condition before trimming comma or before adding ']'.

if (lastCharacter == ",")
{
    trim comma and
    add closing bracket ']'
}
else if (lastCharacter =='}')
{
     add closing bracket ']'
}
else
{
     then do nothing, 
     As json is in correct format with closing bracket
}

To perform this condition checking, I need to get the last character of jsonTxt. But Shows error as "Index and length must refer to a location within the string". Thank you.

CodePudding user response:

I believe the 2nd parameter of String.Substring is used to declare the amount of characters that you want, starting at the specified index.

So for your example it should be something like jsonTxt.Substring(jsonTxt.Length - 1, 1)

Documentation here

  • Related