I have problems to covert an associated array in JavaScript to JSON object.
The problem is as follow: I have an Array which index are Strings and when I use JSON.stringify(myArray)
it returns []
. If I build my Array as an Object the problem is solved and return {"key1":"value1","key2":"value2"}
but the conversi开发者_运维技巧on is different. I want a conversion with my Array object like ["key1":"value1","key2":"value2"]
.
It also works fine when my index are numbers but no when are Strings.
How I can do that? I've search the forum for an answer and I found a lot of info but not something like that.
PD: I will let you an example
var prueba = new Array();
prueba["key1"] = "value1";
prueba["key2"] = "value2";
This dont work when I stringify it.
var prueba = new Object();
prueba["key1"] = "value1";
prueba["key2"] = "value2";
This works fine but the result is not apropiated to deserialize it in other languages (trust me).
var prueba = new Array();
prueba[0] = "value1";
prueba[1] = "value2";
This works exactly I want but with numeric index.
Why not
var input = '{"key1":"value1","key2":"value2"}',
output = input.replace(/^{(.*)}$/, '[$1]');
console.log(output); // >> ["key1":"value1","key2":"value2"]
Here input
is the result of an ordinary JSON.stringify()
, output
is the RegExp'ed input
.
精彩评论