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!
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"}]'
You can even shorten the first four lines to just this:
var sample_array = [{ type: 'I' }];