Check if a key exists in NewtonSoft JObject C #

I have a JSON object (NewtonSoft.JObject). It contains several entries in this format:

{ "id": "b65ngx59-2c67-4f5b-9705-8525d65e1b8", "name": "TestSample", "versions": [] }, { "id": "8acd8343-617f-4354-9b29-87a251d2f3e7", "name": "template 2", "versions": [ { "id": "556ng956-57e1-47d8-9801-9789d47th5a5", "template_id": "8acd8343-617f-4354-9b29-87a251d2f3e7", "active": 1, "name": "1.0", "subject": "<%subject%>", "updated_at": "2015-07-24 08:32:58" } ] } 

Note. Just an example.

I wrote the code to get the identifiers in the list:

 List<JToken> templateIdList = jObj.Descendants() .Where(t => t.Type == JTokenType.Property && ((JProperty)t).Name == "id") .Select(p => ((JProperty)p).Value) .ToList(); 

Note: jObj is a JSON object

Output List:

 [0] - b65ngx59-2c67-4f5b-9705-8525d65e1b8 [1] - 8acd8343-617f-4354-9b29-87a251d2f3e7 [2] - 556ng956-57e1-47d8-9801-9789d47th5a5 

It gives all identifiers. Now I want to add a condition to linq so that only template_ids containing active with value = 1 in them should be populated in the list.

Required Conclusion:

 [0] - 8acd8343-617f-4354-9b29-87a251d2f3e7 

What changes should be made to linq request to get this?

EDIT : full code

 public bool CheckIfTemplateExists(string template) { bool exists = false; //web service call to retrieve jsonTemplates JObject jObj = JObject.Parse(jsonTemplates); List<JToken> templateIdList = jObj.Descendants() .Where(t => t.Type == JTokenType.Property && ((JProperty)t).Name == "id") .Select(p => ((JProperty)p).Value) .ToList(); if(templateIdList.IndexOf(template) != -1) { exists = true; } return exists } 

jsonTemplates in the above code is a format string:

 {"templates": [{"id":"b65cae59-2c67-4f5b-9705-07465d65e1b8", "name":"TestSample","versions":[]}, {"id":"8edb8343-617f-4354-9b29-87a251d2f3e7", "name":"Template1", "versions":[{"id":"556bb956-57e1-47d8-9801-9388d47cc5a5", "template_id":"8edb8343-617f-4354-9b29-87a251d2f3e7", "active":1, "name":"1.0","subject":"\u003c%subject%\u003e", "updated_at":"2015-07-24 08:32:58"}]} 
+5
source share
1 answer

Try the following:

 List<JToken> templateIdList = jObj["templates"].Children() .Where(child => child["versions"] != null && child["versions"].Any(version => version["active"].Value<int>() == 1)) .Select(x => x["id"]); 
+5
source

All Articles