1

I am using the following script to help me convert javascript arrays to json strings: https://github.com/douglascrockford/JSON-js/blob/master/json2.js

How come this works:

var data = [];
data[1] = [];
data[1].push('some info');
data[1].push('some more info');
json_data = JSON.stringify(data);
alert(json_data);

And this does not (returns a blank):

var data = [];
data['abc'] = [];
data['abc'].push('some info');
data['abc'].push('some more info');
json_data = JSON.stringify(data);
alert(json_data);

I want to convert multi-dimensional javascript arrays, but it seems I cannot use stringify() if I name my array keys?

2 Answers 2

2

JSON arrays are integer-indexed only.

You can change your first line to use {} as in http://jsfiddle.net/5YXNk/, which is the best you can do here.

Check the array syntax at http://json.org/ -- note arrays contain values only, which will be implicitly indexed by non-negative integers. That's just the way it is.

1

There is no such thing as an associative array in Javascript. You're going to have to use an object if you want to use string "keys".

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.