每个 JSON 不起作用

JSON foreach not working

本文关键字:不起作用 JSON 每个      更新时间:2023-09-26

>我有以下JSON代码:

{
    "chat": [
        {
            "username": "demo",
            "text": "hi man",
            "time": "1380167419"
        },
        {
            "username": "admin",
            "text": "hi",
            "time": "1380167435"
        },
        {
            "username": "demo",
            "text": "this works flawless now.",
            "time": "1380167436"
        },
        {
            "username": "demo",
            "text": "we basically done/",
            "time": "1380167443"
        }
    ]
}

当我运行时:

var codes = JSON.parse(history); //history is the above JSON.
$.each(codes, function(key, value){
alert(value.chat.username);
});

它没有提醒任何事情,并一直告诉我value.chat.用户名未定义...

我哪里做错了?

不需要解析 JSON。它已经是一个 JSON 对象

$.each(history.chat, function(key, value){
alert(value.username);
});

您还必须循环访问聊天数组并正确引用其项目。

这次你有一个在 value.chat 中定义的对象数组。您需要先选择一个数组元素,然后才能查看 username 。正确的形式是 value.chat[n].username ,其中 n 是数组中的索引。如果要遍历 chat 对象中的数组,则需要执行以下操作:

$.each(codes.chat, function(key, value){
  alert(value.username);
});

请注意,我们现在正在迭代chat,因此我们可以直接处理每个chat元素中的属性。

那是

...因为未定义 .chat,因为未定义

var codes = JSON.parse(history); //history is the above JSON.
$.each(codes.chat, function(key, value){
    alert(value.username);
});