字符串json具有空值

String json has null values

本文关键字:空值 json 字符串      更新时间:2023-09-26

我正在尝试stringify我的json -

for (var i = 0 ; i < lines.length ; i++) {
    var label = lines[i];
    var value = 1;
    item = [];
    item["label"] = label;
    item["value"] = value;
    jsonObj.push(item);
}
var jsonString = JSON.stringify(jsonObj);

在迭代过程中,labelvalue都被分配了正确的值。

然而jsonString充满了空值,为什么会出现这种情况?

应该是item = {};而不是item = [];

第一个是对象字面值,第二个是数组字面值。

为了更好的测量,var items = {};

的情况是,你创建一个数组item = [],然后设置它的字符串属性。

JSON.stringify期望看起来像数组的东西就是数组,所以它甚至不会尝试遍历它的非数字属性。

您的解决方案是将其替换为对象{}

摘自规范:

If Type(value) is Object, and IsCallable(value) is false
    If the [[Class]] internal property of value is "Array" then
        Return the result of calling the abstract operation JA with argument value.

紧随其后
Let len be the result of calling the [[Get]] internal method of value with argument "length".
Let index be 0.
Repeat while index < len
    Let strP be the result of calling the abstract operation Str with arguments ToString(index) and value.
    If strP is undefined
        Append "null" to partial.
    Else
        Append strP to partial.
    Increment index by 1.

引用:

  • 函数15.12.3把
  • 15.12.3 stringify JA

如上所述,您需要将项目设置为对象。这里有一个JSFiddle,可以让您从一个示例开始。

var item;
var lines = ["a","b","c"];
var jsonObj = {};
jsonObj.items = [];
for (var i = 0 ; i < lines.length ; i++) {
    var label = lines[i];
    var value = 1;
    item = {};
   item["label"] = label;
   item["value"] = value;
    jsonObj.items.push(item);
    console.log(jsonObj);
}
var jsonString = JSON.stringify(jsonObj);
console.log(jsonString);