开发者

Serializing a Javascript object with contained arrays to json?

I have a javascript object that contains a few objects that contain associative arrays. I've been trying to use the json2.js library's stringify function but the output doesn't contain the arrays held in the contained object members. In my code I start with something like this

obj = {"arr1" : [], "arr2" : [], "arr3" : [开发者_JAVA百科]};

then I add to it with loops that fill each of the contained arrays

obj[arr*].push[arritem*];
obj[arr*][arritem*] = something;

The arr* and arritem* I put in just to represent the variable I am putting in for the loops. I try Json.stringify(obj) but the string I get back is

'{"arr1" : [0], "arr2" : [0], "arr3" : [0]}'

I would like to see the ouput as

'{"arr1" : [ "arritem1" : something, "arritem2" : something2], "arr2" : [ "arritem1" : something, "arritem2" : something2], "arr3" : [ "arritem1" : something, "arritem2" : something2]}'

is there a better library for this or is there something I have to do before strinfying?


var obj = {"arr1" : [], "arr2" : [], "arr3" : []};
console.log(JSON.stringify(obj));

Works for me.

Filling the arrays works too.


Update

You imply that you are trying to add elements with non-numeric keys to arrays.

This is not valid. In particular, your desired output is not valid JSON. Arrays have only numeric keys, and they are not included in the JSON itself as they are implicitly, sequentially defined.

Arrays are a special type of Object, which handles numeric indexes for you.

var arr = [];   // Create array.
arr.push(1);    // There is now one element, with index 0 and value 1.
arr["txt"] = 2; // You tried to create a new element,
                // but didn't use .push and gave a non-numeric key.
                // This broke your array.

console.log(JSON.stringify(arr));
// Output: [1]

Live demo.

Long story short... don't do this. If you want an "associative array", stick with basic objects:

var obj    = {}; // Create object.
obj[0]     = 1;  // There is now one element, with key "0" and value 1.
obj["txt"] = 2;  // There is now a second element, with key "txt" and value 2.

console.log(JSON.stringify(arr));
// Output: {"0":1,"txt":2}

Live demo.


obj.toSource()

this will convert your array to source string.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜