Stringify JavaScript对象

时间:2013-08-22 14:51:12

标签: javascript json object stringify

我正在寻找一个对象的字符串。

我希望输出像这样

{"1":{"valeur":"dalebrun","usager":"experttasp","date":"2013-08-20 16:41:50"}, "2": {"valeur":"test","usager":"experttasp","date":"2013-08-20 16:41:50"}}

但我得到了这个

{"valeur":"dalebrun","usager":"experttasp","date":"2013-08-20 16:41:50"}, {"valeur":"test","usager":"experttasp","date":"2013-08-20 16:41:50"}

我做什么

var objVal = {}; //value....
var data = {}; //other value....
var object = $.extend({}, objVal, data); //concat the object 
JSON.stringify(object); 

2 个答案:

答案 0 :(得分:6)

当你连接对象时,你得到一个数组;你想要一个带有两个元素的地图,使用id“1”和“2”

var objVal = {};   //value....
var data = {};     //other value....

var object = {}
object["1"] = objVal;
object["2"] = date;
JSON.stringify(object); 

答案 1 :(得分:5)

我找到了解决方案!

我在对象上做了一个for循环。然后我迭代对象中的每个元素。谢谢您的帮助。 @Giovanni的答案帮助我找到了解决方案。

解决方案:

var data = {}; //values....
var objVal = {}; //other values....
var final = {};
var index = 1;
for(var key in data)
{
    final[index] = data[key];
    index = index + 1;
}
final[index] = objVal;
JSON.stringify(final);

输出为:

{"1":{"valeur":"dfgdfg","usager":"experttasp","date":"2013-08-23 10:36:54"},"2":{"valeur":"uuuuuuuuuu","commentaire":"defg","usager":"experttasp","date":"2013-08-23 10:37:26"},"3":{"valeur":"uuuuuuuuuu","commentaire":"yesssss","usager":"experttasp","date":"2013-08-23 10:38:38"}}