【问题标题】:JSON.stringify not display properly, while use multiple javascript objectJSON.stringify 无法正确显示,同时使用多个 javascript 对象
【发布时间】:2016-05-06 23:06:23
【问题描述】:

我已经使用基于我的页面结果生成 javascript 多个对象,然后转换为 JSON 字符串。但JSON.stringify 无法正常显示。不知道为什么会这样显示。我添加了我的编码示例

var sample_object = [];
var sub_array = [];
sub_array["type"] = 'I';
sample_object.push(sub_array);

console.log(sample_object);
console.log(JSON.stringify(sample_object));

结果:-

[Array[0]]
    0: Array[0]
        length: 0
        type: "I"_
        _proto__: Array[0]
        length: 1__proto__:
        Array[0]

JSON.stringify 输出

 [[]]

提前致谢!

【问题讨论】:

  • sub_array["type"] = 'I';此语句将无效

标签: jquery json stringify


【解决方案1】:

这是因为您不能在数组中包含命名参数。您需要将sub_array 更改为一个对象。另请注意,您命名为sample_object 的变量实际上是一个数组。这是一个带有适当命名变量的工作版本:

var sample_array = [];
var sub_object = {};
sub_object["type"] = 'I';
sample_array.push(sub_object);

console.log(sample_array);
console.log(JSON.stringify(sample_array)); // = '[{"type":"I"}]'

Example fiddle

您甚至可以将前四行缩短为:

var sample_array = [{ type: 'I' }];

【讨论】:

  • 感谢您的回答,成功
  • 没问题,很乐意提供帮助。
  • 您可以在 Array 中拥有自定义属性!数组实例也是对象实例...
【解决方案2】:

JSON.stringify 只使用从 0 到 a.length-1 的数组索引,没关系。如果要创建其他属性,请使用 object...

例如

var x={type:"i",data:[]}

【讨论】:

  • 感谢您的帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-24
  • 1970-01-01
  • 2011-08-26
  • 2015-09-01
  • 2010-11-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多