Search code examples
javascriptjsonstringify

String json has null values


I am trying to stringify my 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);

During iteration, both label and value are being assigned accordingly with the correct values.

However jsonString is full of null values, why is this the case?


Solution

  • It should be item = {}; and not item = [];.

    The first is the object literal, and the second is the array literal.

    For good measure, do var items = {};