0

I've been trying to stringify a javascript array which is keyed by strings. JSON always stringifies the array as empty ([]).

var arr = new Array(3);
arr['A'] = "Foo";
arr['B'] = "Bar";
arr['C'] = "Baz";

var str = JSON.stringify(arr);

If I replace the 'A', 'B', 'C' with 0,1,2 then the array is stringified correctly. I'm sure I'm missing something, just not sure what.

Thanks!

2 Answers 2

2

You cant have keys as strings in array, use object for this {}.

var obj = {};
obj['A'] = "Foo";
obj['B'] = "Bar";
obj['C'] = "Baz";

var str = JSON.stringify(obj);
0

You want an Object, not an Array.

JSON.stringify({
  "A": "Foo",
  "B": "Bar",
  "C": "Baz"
});

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.