Search code examples
c#jsonparsingjson.netquerying

Querying JSON with SelectTokens in c#


I need some help with parsing a JObject. The following json is the result of this line of code in c# :

var o = JObject.Parse(data);

o   {{
  "firstdata": {
    "count": 17,
    "firstOccurrence": 1493663381786,
    "lastOccurrence": 1493681141398
  },
  "views": {
    "count": 17,
    "firstOccurrence": 1493663381787,
    "lastOccurrence": 1493681141398
  },
  "session": {
    "count": 57,
    "firstOccurrence": 1493663381787,
    "lastOccurrence": 1493681159212
  },
  "test": {
    "count": 17,
    "firstOccurrence": 1493663381788,
    "lastOccurrence": 1493681141399
  },
  "browser": {
    "count": 17,
    "firstOccurrence": 1493663381788,
    "lastOccurrence": 1493681141399
  },
  "click": {
    "count": 18,
    "firstOccurrence": 1493663381805,
    "lastOccurrence": 1493681141410
  },
  "click.Default": {
    "count": 18,
    "firstOccurrence": 1493663381805,
    "lastOccurrence": 1493681141410
  },
  "click.6": {
    "count": 18,
    "firstOccurrence": 1493663381805,
    "lastOccurrence": 1493681141410
  },
  "generic_Click.mail": {
    "count": 4,
    "firstOccurrence": 1493663488302,
    "lastOccurrence": 1493675499011
  },
  "generic_Click.calander": {
    "count": 3,
    "firstOccurrence": 1493663649203,
    "lastOccurrence": 1493675501110
  },
  "generic_Click.tweet": {
    "count": 2,
    "firstOccurrence": 1493663657444,
    "lastOccurrence": 1493675577793
  },
  "generic_Click.facebook": {
    "count": 3,
    "firstOccurrence": 1493663840925,
    "lastOccurrence": 1493677734366
  }
}}

What I need is to look for all elements in this json object that starts with "generic_click" and store their corresponding "count" values. I tried to look for one of them using this line of code, which returns null.

var test = o.SelectToken("generic_Click.facebook");

My guess is that the dot in "generic_Click.facebook" is causing the SelectToken considering this as a path, rather than a name to look for.

Can anybody help me with this please? I am trying to find a way to return "count" for all elements in this json objects that starts with "generic_Click."

Thanks a lot


Solution

  • You can use a LINQ query to gather the item names and counts into a dictionary:

    Dictionary<string, int> dict = JObject.Parse(data).Properties()
        .Where(p => p.Name.StartsWith("generic_Click"))
        .ToDictionary(p => p.Name, p => (int)p.Value["count"]);
    
    foreach (var kvp in dict)
    {
        Console.WriteLine(kvp.Key + ": " + kvp.Value);
    }
    

    Fiddle: https://dotnetfiddle.net/9Oq4J4