1

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?

1
  • 1
    Just add where ((int)p["minutesStreamed"]) > 60 between your from and select lines. Commented Nov 10, 2015 at 12:13

1 Answer 1

5

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

You can also use [Jsonpath][1] with JToken.SelectTokens(). Also, FYI, you should always use JToken instead of JObject, in the event that the Json you pass in is in the form of an array. JToken is the parent class of both JArray and JObject. [1]: goessner.net/articles/JsonPath

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.