John H
John H

Reputation: 21

Querying Json with filters using Json.Net

In C# I'm using Json.net to try and retrieve the sum total of 'buttonPress' where 'minutesStreamed' is over 60.

string json = @"
{
    'results': [
    {
        'buttonPress': 8,
        'minutesStreamed': 83
    },
    {
        'buttonPress': 3,
        'minutesStreamed': 4
    },
    {
        'buttonPress': 7,
        'minutesStreamed': 61
    }
        ]
    }";

I did this (below) which retrieves the Sum of the entire column, but I can't find a way to filter out anything where minutesStreamed > 60.

JObject obj = JObject.Parse(json);
var buttonPresses=
    from p in obj["results"]
    select (int)p["buttonPress"];

int sum = buttonPresses.Sum();

The desired output would be 15 if it works correctly.

Is this even possible?

Upvotes: 1

Views: 3847

Answers (1)

Arghya C
Arghya C

Reputation: 10078

If you are using Json.NET, you can do this with Linq-to-JSON like this

var jsonString = File.ReadAllText(@"C:\YourDirectory\results.json");
var jObj = JObject.Parse(jsonString);

var sum = jObj["results"]
            .Where(r => (int)r["minutesStreamed"] > 60)
            .Select(r => (int)r["buttonPress"])
            .Sum();

Also, notice that your JSON is not well-formatted, you need to separate properties of an object by comma , like this

{
    'buttonPress': 8, <= this
    'minutesStreamed': 83
}

Upvotes: 5

Related Questions