0

我觉得这很简单,但是,我很难让它吐出undefined以外的任何东西

我希望能够获取将字符串传递给函数的 JSON 对象。这可以通过如下功能实现吗?

var dashboardData= {
"Dashboard": 
{
    "Total_Downloads":95,
    "Unique_Downloads":30,
    "Campaign_Threshold":1000,
    "Downloads_By_Date":[
        {"Downloads":6,"Date":"9/6/2012 12:00:00 AM"},
        {"Downloads":2,"Date":"9/7/2012 12:00:00 AM"},
        {"Downloads":9,"Date":"9/20/2012 12:00:00 AM"},
        {"Downloads":2,"Date":"9/22/2012 12:00:00 AM"},
        {"Downloads":6,"Date":"9/23/2012 12:00:00 AM"},
        {"Downloads":10,"Date":"9/24/2012 12:00:00 AM"},
        {"Downloads":1,"Date":"9/26/2012 12:00:00 AM"},
        {"Downloads":1,"Date":"9/29/2012 12:00:00 AM"},
        {"Downloads":3,"Date":"10/2/2012 12:00:00 AM"},
        {"Downloads":4,"Date":"10/5/2012 12:00:00 AM"},
        {"Downloads":1,"Date":"10/6/2012 12:00:00 AM"},
        {"Downloads":2,"Date":"10/8/2012 12:00:00 AM"},
        {"Downloads":4,"Date":"10/9/2012 12:00:00 AM"},
        {"Downloads":3,"Date":"10/10/2012 12:00:00 AM"},
        {"Downloads":1,"Date":"10/12/2012 12:00:00 AM"},
        {"Downloads":27,"Date":"10/16/2012 12:00:00 AM"},
        {"Downloads":2,"Date":"10/17/2012 12:00:00 AM"},
        {"Downloads":1,"Date":"10/19/2012 12:00:00 AM"},
        {"Downloads":1,"Date":"10/20/2012 12:00:00 AM"},
        {"Downloads":9,"Date":"10/21/2012 12:00:00 AM"}
    ],
  }
};

        function formatJSON(source, key1, key2) {

            var i, l,
                dest = [],
                row;

            for(i = 0, l = source.length; i < l; i++) {
                row = source[i];      

                 dest.push('[' + row.key1, row.key2 + ']');

            }

            return '[' + dest + ']';

        }

var downloads= formatJSON(dashboardData.Dashboard.Downloads_By_Date,'Downloads','Date');     

var output="<ul>";
output+="<li>" + dashboardData.Dashboard.Total_Downloads + "</li>";

output+="</ul>";
document.getElementById("placeholder").innerHTML=downloads;

​</p>

4

2 回答 2

0

JSON.stringify本身有一些格式化选项。例如,您可以通过将“4”作为第三个参数将其缩进 4 个空格:Demo at jsfiddle.net

于 2012-10-22T00:22:48.303 回答
0

您要求的是行对象的 key1 和 key2 属性,而不是键所代表的属性。

dest.push('[' + row[key1] + ',' + row[key2] + ']');

于 2012-10-22T00:23:01.910 回答