Home > Blockchain >  Extracting nested data from JSON array
Extracting nested data from JSON array

Time:01-21

I am trying to extract the following fields from the JSON feed at the bottom of this post into a C# object.

"Bronze",
[
  228,
  380  
]

C# Object Structure:

public Score 
{
  public string Grade {get;set;} // Bronze, Silver, Gold
  public int PotentialPoints {get;set;} // First Integer
  public int ActualPoints {get;set;} // Second Integer
}

The Feed

The string "Bronze" is variable, but the integer array structure will stay the same [X,X].

[
   6,
   [
      [],
      4,
      {
         "time crunch":[
            "Bronze", <<< Trying to retrieve this node
            [
               228,
               380  
            ]
         ],
         "3 rides":[
            "Bronze", <<< Trying to retrieve this node
            [
               1418,
               2730
            ]
         ],
         "4 rides":[
            "Bronze", <<< Trying to retrieve this node
            [
               180,
               320
            ]
         ],
         "[2 rides,2 runs]":[
            "Silver", <<< Trying to retrieve this node
            [
               220,
               270
            ]
         ]
      }
   ]
]

CodePudding user response:

This could be done a lot better but with the JSON you provided, it works ...

static void ExtractNodes()
{
    string json = "[6,[[],4,{\"time crunch\":[\"Bronze\",[228,380]],\"3 rides\":[\"Bronze\",[1418,2730]],\"4 rides\":[\"Bronze\",[180,320]],\"[2 rides,2 runs]\":[\"Silver\",[220,270]]}]]";

    var jArray = JArray.Parse(json);

    var data = jArray.SelectTokens("$..*")
        .Where(x => x.Type == JTokenType.Array)
        .Where(x => x.First != null)
        .Where(x => x.First.Type == JTokenType.String)
        .Select(x => new Score()
        {
            Grade = (String)x.First,
            PotentialPoints = (int)((JArray)x.Children().ElementAt(1)).Children().ElementAt(0),
            ActualPoints = (int)((JArray)x.Children().ElementAt(1)).Children().ElementAt(1)
        });
}

Feel free to wait for other answers.

CodePudding user response:

If your JSON has a standard schema, you can extract the data with JSON path.

using Newtonsoft.Json.Linq;

var result = JArray.Parse(json).SelectToken("$.[1].[2]")
    .ToObject<Dictionary<string, JArray>>()
    .Select(x => new Score
        {
            Grade = x.Value.SelectToken("[0]").ToString(),
            PotentialPoints =  x.Value.SelectToken("[1].[0]").ToObject<int>(),
            ActualPoints =  x.Value.SelectToken("[1].[1]").ToObject<int>()
        })
    .ToList();

Demo @ .NET Fiddle

  • Related