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}
5
  • 5
    you cant have same property name multiple times in an object {"categories":1,"categories":2, "categories":3} => {"categories":3} Commented Jun 20, 2016 at 4:46
  • Thank you for your quick response. Anyone please suggest me the best idea to send multiple checkbox value through ajax? Commented Jun 20, 2016 at 4:56
  • 2
    What you can probably aim for is {"categories": [1,2,3]} Commented Jun 20, 2016 at 4:56
  • 1
    Fore serializing a form use serialize() or serializeArray() Commented Jun 20, 2016 at 5:04
  • Thank You Pranav C Balan and Rajesh Yogeshwar. This Now I am going through {"categories": [1,2,3]}. And this is working. Thank You again. Commented Jun 20, 2016 at 5:07

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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}

Comments

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.