将多个json字符串转换为一个字符串

时间:2017-01-05 10:31:49

标签: jquery json ajax

我想将多个json字符串转换为单个字符串。

这是我的多个json字符串如何将其转换为单个字符串。我将此字符串作为ajax的响应。

[  
   {  
      "name1":"pizaa",
      "count1":8
   },
   {  
      "name2":"sandvich",
      "count2":8
   },
   {  
      "name3":"Burger",
      "count3":8
   },
   {  
      "name4":"TEST category",
      "count4":8
   },
   {  
      "name5":"TEST category",
      "count5":8
   },
   {  
      "name6":"TEST category",
      "count6":8
   },
   {  
      "name7":"final test",
      "count7":8
   },
   {  
      "name8":"final final test",
      "count8":8
   }
]

输出如下:

   [  
   {  
      "name1":"pizaa",
      "count1":8,
      "name2":"sandvich",
      "count2":8
   }
   ]

3 个答案:

答案 0 :(得分:1)

我在jsfiddle创建了一个解决方案。在这里,我使用了JSON.stringify

var json = [{
  "name1": "pizaa",
  "count": 8
}, {
  "name2": "sandvich",
  "count": 8
}, {
  "name3": "Burger",
  "count": 8
}, {
  "name4": "TEST category",
  "count": 8
}, {
  "name5": "TEST category",
  "count": 8
}, {
  "name6": "TEST category",
  "count": 8
}, {
  "name7": "final test",
  "count": 8
}, {
  "name8": "final final test",
  "count": 8
}]

var finalString = '';
finalString = JSON.stringify(json);
finalString = finalString.replace(/},{/g, ",");
alert(finalString);

答案 1 :(得分:0)

我试图为您的问题发布解决方案。看看:



var data = [  
   {  
      "name1":"pizaa",
      "count1":8
   },
   {  
      "name2":"sandvich",
      "count2":8
   },
   {  
      "name3":"Burger",
      "count3":8
   },
   {  
      "name4":"TEST category",
      "count4":8
   },
   {  
      "name5":"TEST category",
      "count5":8
   },
   {  
      "name6":"TEST category",
      "count6":8
   },
   {  
      "name7":"final test",
      "count7":8
   },
   {  
      "name8":"final final test",
      "count8":8
   }
];

var result = [];
var reduced = {};
data.map(function(a) {
  for(var p in a) {
    reduced[p] = a[p];
  }
});
result[0] = reduced;
console.log(result);




答案 2 :(得分:0)

试试这个:

var jsonData = [{"name1":"pizaa","count1":8},{"name2":"sandvich","count2":8},{"name3":"Burger","count3":8},{"name4":"TEST category","count4":8},{"name5":"TEST category","count5":8},{"name6":"TEST category","count6":8},{"name7":"final test","count7":8},{"name8":"final final test","count8":8}];
var modJson = {};
$.each(jsonData, function(index, val) {
  modJson['name'+(index+1)] = val['name'+(index+1)];
  modJson['count'+(index+1)] = val['count'+(index+1)];
});
console.log(modJson);