0

I have an array like

["categories", 1, "categories", 2, "categories", 3]

I want to convert this array to JSON format like

{"categories":1,"categories":2, "categories":3}
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
bikram kc
  • 846
  • 1
  • 14
  • 18

3 Answers3

1

You can convert an array into JSON with:

var a = ["categories", 1, "categories", 2, "categories", 3];
var json = JSON.stringify(a);
// json will be: "["categories",1,"categories",2,"categories",3]"

The JSON string you have in your question is not an array, it is an object. And as Pranav pointed out in his comment, it is an invalid object notation, because the properties of an object have to be unique.

Maikel
  • 514
  • 4
  • 9
1

In such case We will have to go through {"categories": [1,2,3]}. for this we have to create a array of values and create a JSON data {"categories": [1,2,3]}.

This solves the problem to post multiple values of same field like checkbox through ajax.

bikram kc
  • 846
  • 1
  • 14
  • 18
0

if you means this

["categories1", 1, "categories2", 2, "categories3", 3]

each key is different, then you can go with

var a = ["categories1", 1, "categories2", 2, "categories2", 3],
    b = {}, len = a.length;

for(i=0; i<len; i+=2){
    var key = a[i], val = a[i+1];
    b[key] = val
}

// b should be {"categories1":1,"categories2":2, "categories3":3}

if not, just like @Pranav C Balan said, you can't have three identical keys in one object, they will simply override the previous ones;

you might also need this underscore method, really handy

_.object(['moe', 'larry', 'curly'], [30, 40, 50]);
=> {moe: 30, larry: 40, curly: 50}

_.object([['moe', 30], ['larry', 40], ['curly', 50]]);
=> {moe: 30, larry: 40, curly: 50}
Newset
  • 91
  • 1
  • 9