Search code examples
c#.netlinqjson.net

Get count of column based on condition inside JSON


Requirement is to get count of column based on condition inside JSON string

string jsonString = """{"data":"key = IAfpK, age = 58, key = WNVdi, age = 64"}""";

Condition age >= 50

Count of Age = 2

Option 1

I tried to deserialize JSON to a model first

public class JsonModel
{
    public string Name { get; set; }

    public int Age { get; set; }
}

var resultList = JsonConvert.DeserializeObject<JsonModel>(s);

List<JsonModel> result = items.Where(x => x.Age >= 50).ToList();// doesnt work

Console.WriteLine(result.Count());

Option 2

        dynamic obj = JObject.Parse(s);
        var a = obj.data[0]; //Cannot access child value on Newtonsoft.Json.Linq.JValue.'
        string error = a.age;

Option 3

dynamic obj = JObject.Parse(s);
    var a = obj.data["age"]; //Cannot access child value on Newtonsoft.Json.Linq.JValue.'
    

Tried few options it's not working, how do I get the count?

Option 4

static async Task Main(string[] args)
    {
       
        HttpClient client = new HttpClient();
        var s = await client.GetStringAsync("https://coderbyte.com/api/challenges/json/age-counting");
        var jsonLinq = JObject.Parse(s);


 foreach (var package in jsonLinq)
        {
            string[] values = package.Value.ToString().Split(',');
            //var res = values.Where(String.Format("age=50"));

            List<string> list = new List<string>();
            list.AddRange(values);
            
        }
           }

Solution

  • You should split data property string value and parse by yourself.

    static async Task Main(string[] args)
    {
        HttpClient client = new HttpClient();
    
        var jsonStr = await client.GetStringAsync("https://coderbyte.com/api/challenges/json/age-counting");
        var parsed = JsonDocument.Parse(jsonStr);
        var dataString = parsed.RootElement.GetProperty("data").GetString();
    
        if (dataString != null)
        {
            var pairs = dataString.Split(", ");
            var items = new List<(string Key, int Age)>();
    
            for (var index = 0; index < pairs.Length; index += 2)
            {
                if (index + 1 >= pairs.Length)
                    break;
    
                var firstPair = pairs[index].Split("=");
                var secondPair = pairs[index + 1].Split("=");
    
                if (firstPair.Length != 2 || secondPair.Length != 2)
                    continue;
    
                if (firstPair[0] != "key" || secondPair[0] != "age")
                    continue;
    
                items.Add((Key: firstPair[1], Age: int.Parse(secondPair[1])));
            }
    
            var count = items.Count(x => x.Age >= 50);
        }
    }