1

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?

1
  • You are trying to stringify a collection of 2 strings, that won't do, since JSON.stringify expects an OBJECT to stringify. See my answer below for correct syntax ;) Commented Aug 30, 2017 at 14:46

4 Answers 4

4

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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
};)

Comments

1

why not:

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

Comments

1

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.

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.