使用javascript创建jsonstring

时间:2015-07-16 02:08:34

标签: javascript

我正在构建一个json数组,我需要json数据的结构,如下面的示例所示。具体来说,我需要“成功”:1,并且“结果”:[]仅在ONCE中包围数组中的对象。但是,我的代码在每个数组开始之前输出带有{“success”:1,“result”:[{objects}}的json字符串。

这是我的行动代码。 http://plnkr.co/edit/vziEecjJWUid2qtcJkp9?p=preview

查看你的console.log以查看它在“success”中循环的位置:1,以及每个数组开头的“result”:[]。

我需要的例子。

{  
   "success":1,
   "result":[
      {  
         "id":"01",
         "title":"awesome title",
         "url":"someurl.com",
         "class":"event",
         "start":"8:30 AM",
         "startTime":"8:30 AM",
         "endTime":"5:00 PM",
         "EventDate":"5:00 PM"
      },
      {  
         "id":"01",
         "title":"awesome title",
         "url":"someurl.com",
         "class":"event",
         "start":"8:30 AM",
         "startTime":"8:30 AM",
         "endTime":"5:00 PM",
         "EventDate":"5:00 PM"
      }
 ]
}

我目前的json结构(不好):

{"success":1,"result":[{  
         "id":"01",
         "title":"awesome title",
         "url":"someurl.com",
         "class":"event",
         "start":"8:30 AM",
         "startTime":"8:30 AM",
         "endTime":"5:00 PM",
         "EventDate":"5:00 PM"
      }] }

{"success":1,"result":[{  
         "id":"01",
         "title":"awesome title",
         "url":"someurl.com",
         "class":"event",
         "start":"8:30 AM",
         "startTime":"8:30 AM",
         "endTime":"5:00 PM",
         "EventDate":"5:00 PM"
      }] }

2 个答案:

答案 0 :(得分:1)

在这种情况下,

JSON.stringify()是你的朋友。只需使用stringify(),你就会做标准的事情。就像你展示它一样组装你的对象。

如果您需要特定的文本格式,而不是stringify()的默认格式(紧凑),您可以使用参数stringify()来获取特定于项目的替换函数。我建议检查MDN文档https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

答案 1 :(得分:0)

将你的arr置于for循环之下。

并在for loop scope之后打印final arr

试试这个

var arr = {
    "success": 1,
    result: []
};


var entryLenght = result.feed.entries.length;
// console.log("Number of posts: " + entryLenght);
for (var i = 0; i < entryLenght; i++) {
    //console.log("Loop: " + i);
    var entry = result.feed.entries[i];
    var myObject = {
        id: "01",
        title: entry.title ,
        url: entry.link,
        class: "event-warning",
        start: "8:30am",
        startTime: "8:30am",
        endTime: "5:30pm"
    };
    //console.log(myObject);

    arr.result.push(myObject); // push your prepared object to arr.result

    var html = '<li>' +
        '<h3>' + entry.title + '</h3>' +
        '<h4>' + entry.categories[0] + '</h4>' +
        '<p>Info: ' + entry.contentSnippet + '</p>' +
        //'<p>' + startTime + ' - '+ endTime + '</p>'+
        '</li>';
    container.append(html);

}
var json = JSON.stringify(arr);
console.log(json);

PLUNKR