Roeland
Roeland

Reputation: 3858

Trying to convert multi level javascript array to json, with json2 script

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?

Upvotes: 1

Views: 811

Answers (2)

Ray Toal
Ray Toal

Reputation: 88378

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.

Upvotes: 2

Joe
Joe

Reputation: 146

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".

Upvotes: 1

Related Questions