mwill
mwill

Reputation: 434

How do I query this JSON string using LINQ?

I'm very new to LINQ and have done some SO searches on querying a JSON payload but have not found anything quite like I need. Below is my JSON. I'm using .NET with the Newtonsoft Library. The requirements for the query are:

1) How many LogResults have a stat "Frequency" of value "Low"? (in this case, 1)

2) If there is exactly 1 LogResult with "Frequency" = "Low", select all the properties in a flattened object (ID, FName, LName, Frequency, LowRange, HighRange, Temp, Wind)

Is it possible to answer these questions in 1 query? Here is sample JSON with 2 entries in the LogResults array. The array will always contain at least 1 entry and may have many more.

{  
    "LogResults":[  
        {  
             "ID":300,
             "FName":"Jim",
             "LName":"Smith",
             "Stats":{  
                 "Frequency":"Low",
                 "LowRange":"1",
                 "HighRange":"100",
                 "Parameters":{  
                     "Temp":"32",
                     "Wind":"5"
                 }
             }
         },
         {
             "ID":400,
             "FName":"John",
             "LName":"Warren",
             "Stats":{  
                 "Frequency":"Medium",
                 "LowRange":"1",
                 "HighRange":"100",
                 "Parameters":{  
                     "Temp":"21",
                     "Wind":"15"
                 }
             }
         }
     ]
 }

Upvotes: 2

Views: 2662

Answers (1)

t3chb0t
t3chb0t

Reputation: 18675

If you can use json.net you can query json with linq:

// Parse json first.
JObject o = JObject.Parse(json);   

1) How many LogResults have a stat "Frequency" of value "Low"? (in this case, 1)

var result1 = 
    o["LogResults"]
    .Where(t => t["Stats"].Value<string>("Frequency") == "Low")
    .ToList();

2) If there is exactly 1 LogResult with "Frequency" = "Low", select all the properties in a flattened object (ID, FName, LName, Frequency, LowRange, HighRange, Temp, Wind)

if (result1.Count == 1)
{
    var result2 = result1.Select(t => new
    {
        ID = t.Value<string>("ID"),
        FName = t.Value<string>("FName"),
        LName = t.Value<string>("LName"),
        Frequency = t["Stats"].Value<string>("Frequency"),
        LowRange = t["Stats"].Value<string>("LowRange"),
        HighRange = t["Stats"].Value<string>("HighRange"),
        Temp = t["Stats"]["Parameters"].Value<string>("Temp"),
        Wind = t["Stats"]["Parameters"].Value<string>("Wind")
    }).ToList();
}

Other examples and how to create json declaratively you'll find in its LINQ to JSON documentation.

Upvotes: 4

Related Questions