1

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.

3
  • 2
    Using objects is the only way... your statement about it being difficult to deserialize it in other languages does not make sense. JSON is JSON. If you have a JSON parser for your language, it will create the appropriate data structure in that language. The result you want, ["key1":"value1","key2":"value2"], is not JSON. You cannot make JSON.stringify produce invalid JSON. If you really want that format, then you have to create your own serializer. Commented Oct 13, 2011 at 9:08
  • Perhaps this will aid: developer.mozilla.org/en/… Commented Oct 13, 2011 at 9:12
  • The problem is that if I mapping a structure in JAVA to retrieve my JSON array from JavaScript... the language expects an Object, not an Array. I thought it was easy to fix in JavaScript more than in JAVA but... if you are right I have to parse it better in JAVA >_< Thank you so much! Commented Oct 13, 2011 at 9:21

1 Answer 1

0

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.

2
  • If I can stringify output... that will be nice! but Felix is right, ["key1":"value1"] is not a correct JSON string. Probably what I looking for is {["key1", "value1"]} but with RegExp will be easy. Thanks! Commented Oct 13, 2011 at 9:28
  • Yeah, make the output = input.replace(/^{(.*)}$/, '{[$1]}'); Commented Oct 13, 2011 at 9:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.