Reputation: 39
I saw in another post someone identifying if json is nested or not if it contains a second object after the first then it will return true if not false, in JavaScript
Here is their method. Can we achieve this using C#
function check_if_nested(obj) {
check_nest=[]
obj.map(function(e,i) {$.each(e, function(v){
if(typeof(obj[0][v])=='object') {check_nest.push('nested')} else {check_nest.push('not nested')}
})})
if(check_nest.includes('nested')) {return(true)} else {return(false)}
}
//Not nested
obj_1 = [{
one: "apples",
two: "oranges"
}]
Usage: check_if_nested(obj_1)
output: false
obj_2 = [{
one: "apples",
two: "oranges",
children: [{
three: "bananas",
four: "jicamas"
}]
}]
output: true
Upvotes: 0
Views: 338
Reputation: 81563
Maybe Newtonsoft.Json
var jObject = JObject.Parse(json);
var nested = jObject.Children().Any(x => x.Children().Any(y => y.HasValues));
// or maybe a little easier to read
var nested = JObject.Parse(json)
.Values()
.Any(x => x.HasValues);
Disclaimer : This is completely untested and as such I absolve myself of any responsible for the people you maim or otherwise harm with this code
Update
var token = JToken.Parse(asd2);
bool result;
if (token.Type == JTokenType.Array)
result = token.Children().Any(x => x.Values().Any(y => y.HasValues));
else
result =token.Values().Any(x => x.HasValues);
Upvotes: 3