Search code examples
jqueryjsonstringify

JSON.stringify not display properly, while use multiple javascript object


I have use generate the javascript multiple object based my page result, then convert to JSON string. but JSON.stringify not display properly. I don't know why display like this. I have added example of my coding

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));

Result :-

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

JSON.stringify Output

 [[]]

Thanks in advance!


Solution

  • It's because you can't have named arguments in an array. You need to change sub_array to an object. Also note that the variable you have named sample_object is actually an array. Here's a working version with appropriately named variables:

    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

    You can even shorten the first four lines to just this:

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