将字符串传递给格式化JSON jquery的函数

时间:2012-10-21 23:50:05

标签: javascript jquery json

我觉得这很简单,但是,除了未定义

之外,我很难将其吐出来

我希望能够抓取传入字符串的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;

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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

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