1

I'm trying to stringify multiple arrays, but unsuccessfully

var arr=new Array();
arr['do']='smth';
arr['asd']=[];
arr['asd']['dsa']='alo';
var string=JSON.stringify(arr)
console.log(arr);
console.log(string);

JSON.stringify returns []

5 Answers 5

2

You're creating an array, and use it as if it was a json object. You should create an object if you need an object.

var obj={};
obj['do']='smth';
obj['asd']=[];
obj['asd']['dsa']='alo';
var string=JSON.stringify(obj)
console.log(obj);
console.log(string);
Sign up to request clarification or add additional context in comments.

1 Comment

You just suggested he name an object arr. downvote for just making it even more confusing for him.
2

If you want to use named keys in javascript, you should use an object as the JSON serializer ignores any named keys in arrays. A rule of thumb is that you should use arrays for [0], [1] etc., but objects for ['foo'], ['bar'] etc.

var obj = {
    'do': 'smth',
    'asd': {
        'dsa': 'alo'
    }
};

console.log( JSON.stringify(obj) );
//{"do":"smth","asd":{"dsa":"alo"}} 

3 Comments

Did you mean named keys don't exist in arrays?
The keys do exist, but they're ignored by the JSON serializer.
@Pointy You're right - I changed my description a bit. It seems that Chrome's own console can't even output the variable right (run OP's code - type arr and you get nothing, but console.log(arr) does.)
1

Use an object:

var object = {};
object['do']='smth';
object['asd']=[];
object['asd']['dsa']='alo';
var string=JSON.stringify(object)
console.log(object);
console.log(string);

Comments

0

You cannot give the elements in an array names, they have their indizes as names. So if you would like to give them names use an JS-Object otherwise use the indizies in the definition as follows:

arr[0]='smth';
arr[1]=[];
arr[1][0]='alo';

Comments

0

Remember that JSON stands for javascript object notation , you should have objects with the required properties instead you are creating an array so replace your arrays with {} and add to this

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.