gpt4 book ai didi

javascript - Json解析嵌套数组

转载 作者:行者123 更新时间:2023-11-28 19:28:44 25 4
gpt4 key购买 nike

我一直引用这篇文章Access / process (nested) objects, arrays or JSON ,我们没有运气弄清楚这一点:

我有从 http 请求中获取的 JSON:在我的应用程序中,我需要询问 Posts 对象。

    { 
"email" : "test@email.com",
"username" : "rambo",
"fullname" : "Michael Stalone",
"posts" : [
{ "username" : "Bad Man",
"comments" :
[
{ "com_user" : "michael", "com_post" : "good stuff" },
{ "com_user" : "alex", "com_post" : "hell yes" }
]
},
{ "username" : "CheckerTats",
"comments" : [
{ "com_user" : "basky", "com_post" : "wow awesome" }
]
}
]
}

我明白了,一切都应该是这样的。我还注意到它返回数组对象,因此我索引了变量并将其分配给:var items = data[0]。 console.log(data[0]) 显示:

{
"email":"test@email.com",
"username":"rambo",
"fullname":"Michael Stalone",
"posts":["[object Object]","[object Object]"]
}

所以这一切都很好,而且意识到我需要更进一步并调查数据[0]['posts'][0],结果显示:

[object Object]

我现在几乎可以肯定这是第一个帖子对象。我认为 data[0]['posts'][0]['username'] 会给我那个特定的用户名。更糟糕的是,我的开发环境是一个 iOS Apache Cordova 应用程序,因此当我在其上运行 console.log 时,我什么也没有返回。我已将其分配给变量,使用 stringify、点表示法,但我仍然无法连续访问它目的。我需要这样做才能将其分配给 Angular 范围变量。

编辑:

新日志现在返回未定义:

 var items = dat[0]['posts'][0];
console.log(items['username']); // undefined

最佳答案

仔细观察 data[0]:posts 包含一个由两个字符串组成的数组,表示“[object Object]”,而不是两个对象。你是如何解析 json 的?

哦,您的语法对于从嵌套对象中提取用户名是正确的

关于javascript - Json解析嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27309832/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com