简体   繁体   English

如何将两个JavaScript数组合并为一个JSON?

[英]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. 我想发送两个数组$scope.candidates$scope.managers作为POST到一些我将为服务器编码的PHP。 I strongly prefer a JSON interface, and thought to combine them into a single JSON object. 我非常喜欢JSON接口,并考虑将它们组合成一个JSON对象。

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

Does not generate valid JSON. 不生成有效的JSON。 How do I achieve what I want? 我如何实现自己想要的?

JSON is a format, there is no "JSON object". JSON是一种格式,没有“ JSON对象”。

Create the whole object that you want to send and then generate the JSON string: 创建要发送的整个对象,然后生成JSON字符串:

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

var myJson=JSON.stringify(myObj);

why not: 为什么不:

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

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. 请记住,JSON.stringify适用于对象,而不适用于集合或字符串。

I'm not exactly sure what you want? 我不确定你想要什么吗? Do you want JSON-serialized strings embedded within JSON? 是否要在JSON中嵌入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? 还是只需要一个同时包含candidatesmanagers大型JSON对象作为JSON列表?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM