【问题标题】:How can we check if the json is nested or not?我们如何检查 json 是否嵌套?
【发布时间】:2020-07-17 04:44:28
【问题描述】:

我在另一篇文章中看到有人识别 json 是否嵌套,如果它在第一个对象之后包含第二个对象,那么它将在 JavaScript 中返回 true 如果不是 false

这是他们的方法。我们可以使用 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

【问题讨论】:

    标签: c# json api


    【解决方案1】:

    也许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);
    

    免责声明:这是完全未经测试的,因此我免除自己对您使用此代码致残或以其他方式伤害的人的任何责任

    更新

    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);
    

    【讨论】:

    • 谢谢@TheGeneral。有时我也会得到一个数组.. 我是否应该设置一个 if 条件并使用 JArray.Parse.. 如果我可以如何检查第二个
    • 我有类似的东西,但没有展示如何检查 Json Array 的第二个属性。我已经更新了问题
    • @KevinDavis965 好的,我帮你看看
    • @KevinDavis965 已更新,看看这是否适合您
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-22
    • 2019-06-13
    • 1970-01-01
    • 2013-03-01
    • 2023-03-09
    • 1970-01-01
    • 2023-03-15
    相关资源
    最近更新 更多