On a tech site, I posed this question:
With the following json
{
“Count”:0,
“Message”:{
“AppId”:0
},
“Data”:"[{“application_name”: “Grand Central”,“feature_name”: “1 Click Fix”,“access_type_id”: 2,“member_name”: “GC_Remote_Support_Security”},{“application_name”: “Grand Central”,“feature_name”: “Account Details”,“access_type_id”: 2,“member_name”: “GC_Remote_Support_Security”},{“application_name”: “Grand Central”,“feature_name”: “Account Summary”,“access_type_id”: 2,“member_name”: “GC_Remote_Support_Security”}]"
}
How do I go through the Data array, in the most succinct coding manner possible, to see if any feature_name matches a given string?
This was an answer:
var testString = “Account Summary”;
var found = JToken.Parse(JObject.Parse(jsonString)[“Data”].ToString()).SelectTokens("…feature_name").Any(t => (string)t == testString);
Debug.Assert(found == true); // No assert.
So far, so good.
Now I want to get the actual item that matches the feature name. How do I do it? I can’t figure it out and really need to get this to work for my job.
I’d like to do it with linq like the first one, but any method is fine.
If I understand correctly:
(this is just plain javascript, i don’t know that fancy linq stuff. also, i use the evil eval() function! which must be what your JObject.parse() does)
var json= {
"Count":10,
"Message":{
"AppId":0
},
"Data":"[{\"application_name\": \"Grand Central\",\"feature_name\": \"1 Click Fix\",\"access_type_id\": 2,\"member_name\": \"GC_Remote_Support_Security\"},{\"application_name\": \"Grand Central\",\"feature_name\": \"Account Details\",\"access_type_id\": 2,\"member_name\": \"GC_Remote_Support_Security\"},{\"application_name\": \"Grand Central\",\"feature_name\": \"Account Summary\",\"access_type_id\": 2,\"member_name\": \"GC_Remote_Support_Security\"}]"
};
var testString = "Account Summary";
var dataComponent = eval(json.Data);
for (var data in dataComponent) {
featureName = dataComponent[data]['feature_name'];
if (featureName == testString) {
alert(JSON.stringify(dataComponent[data]));
}
}
Thanks. I forgot to mention this is C#, and JToken/JObject are Newtonsoft. I’d really like to do this with LINQ though. I feel it’s just beyond my grasp. And that I need a similar function to “Any” being used. Anyone?
Off the top of my head…
Instead of using JToken.Parse/SelectToken to pull out a given field from your object you’ll just use the list referenced by JObject.Parse(jsonString)[“Data”]. Instead of using List.Any() you’ll want to use List.Find(). Assuming the list is a list of Map<String, String>, your predicate test will try to get the value corresponding to key “feature_name” and return true only if it exists and the value is “Account Summary”.