【问题标题】:JSON.stringify: JSON string will be empty [duplicate]JSON.stringify:JSON 字符串将为空 [重复]
【发布时间】:2017-01-21 18:28:15
【问题描述】:
var clients = [];

var tmp = [];

tmp["username"] = rows[0].username;
tmp["rank"] = rows[0].rank;
tmp["lastaction"] = "0";
tmp["connection"] = connection;
clients.push(tmp);

JSON.stringify(clients)

我初始化了一个数组 (clients) 并将一个关联数组 (tmp) 推送到 clients 数组。 但是如果我“字符串化”客户端,它只会返回“[[]]”。

我做错了什么?

提前谢谢你。

【问题讨论】:

  • 尝试如下。变量 tmp = {}; js中没有关联数组的概念。它是 json 对象。

标签: javascript json node.js


【解决方案1】:

您应该将tmp 转换为对象文字而不是数组文字。

var clients = [];

var tmp = {};

tmp["username"] = "foo";
tmp["rank"] = 1;
tmp["lastaction"] = "0";
tmp["connection"] = "bar";
clients.push(tmp);

console.log(JSON.stringify(clients))

【讨论】:

    【解决方案2】:

    像这样更新你的代码

    var tmp = {};
    

    关联数组不支持直接在javascript中你可以作为对象

    【讨论】:

    • 谢谢,但是发送到node.js客户端时会报错:connection.sendUTF(JSON.stringify({response: "loginsucceed", onlinelist: JSON.stringify(clients)} )); “TypeError:将循环结构转换为 JSON”
    • 请点击此链接可能会对您有所帮助stackoverflow.com/questions/11616630/…
    【解决方案3】:

    你需要将tmp初始化为一个对象:

    var clients = [];
    
    var tmp = {};
    
    tmp["username"] = 'username';
    tmp["rank"] = 1
    tmp["lastaction"] = 2
    tmp["connection"] = 3
    clients.push(tmp);
    
    console.log(JSON.stringify(clients));

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-12
      • 2014-05-25
      • 1970-01-01
      • 2018-11-28
      • 2014-11-12
      • 1970-01-01
      • 2015-06-02
      • 2013-08-03
      相关资源
      最近更新 更多