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 conversion 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.
["key1":"value1","key2":"value2"]
, is not JSON. You cannot makeJSON.stringify
produce invalid JSON. If you really want that format, then you have to create your own serializer.