Mawg
Mawg

Reputation: 40140

How to combine two JavaScript arrays into one JSON?

I want send two arrays $scope.candidates and $scope.managers as POST to some PHP which I will code for the server. I strongly prefer a JSON interface, and thought to combine them into a single JSON object.

    var JsonString = {'candiates' : JSON.stringify($scope.candidates),
                      'managers'  : JSON.stringify($scope.managers)
                     };

Does not generate valid JSON. How do I achieve what I want?

Upvotes: 1

Views: 89

Answers (4)

Pablo Lozano
Pablo Lozano

Reputation: 10342

JSON is a format, there is no "JSON object".

Create the whole object that you want to send and then generate the JSON string:

var myObj= {
  candidates: $scope.candidates,
  managers: $scope.managers
}

var myJson=JSON.stringify(myObj);

Upvotes: 4

CodeSmith
CodeSmith

Reputation: 3197

Make a single object then stringify that object!

var both = {
   candidates : $scope.candidates,
   managers : $scope.managers
}

then:

var JsonString = JSON.stringify(both)

Remember JSON.stringify works on objects, not collections or strings.

Upvotes: 1

alecbz
alecbz

Reputation: 6488

I'm not exactly sure what you want? Do you want JSON-serialized strings embedded within JSON?

var JsonString = JSON.stringify({
  'candiates' : JSON.stringify($scope.candidates),
  'managers'  : JSON.stringify($scope.managers)
};)

Or do you just want one large JSON object with both candidates and managers as JSON lists?

var JsonString = JSON.stringify({
  'candiates' : $scope.candidates,
  'managers'  : $scope.managers
};)

Upvotes: 1

Matteo Ragni
Matteo Ragni

Reputation: 2956

why not:

var JsonString = JSON.stringify({ 
      candidates: $scope.candidates, 
      managers: $scope.managers 
    });

Upvotes: 1

Related Questions