调整旧的Javascript / jQuery代码以使用不同的JSON格式

时间:2014-08-26 12:42:29

标签: javascript jquery json

我有一个javascript / jQuery脚本,它接受json对象,然后在表中对它们做一些事情

这是JS / jQuery的相关部分

        $.getJSON("People.json",
                function(data) {
                    content = '<tr>';
                    content += '<tbody>';
                    $.each(data.People, function(i, PersonObj) {
                        var Person = PersonObj[Object.keys(PersonObj)[0]];

这个代码片段采用了以下格式的JSON对象,

{
"People": [
    {
        "Person1": {
            "Op": "5709",
            "Name": "Persons name",
            "WorkHours": 5,
            "Start": " 3:00PM",
            "End": " 8:00PM",
            "Clock": false,
            "OFF": false,
            "ON": false,
            "OUT": false,
            "Late": 23484360,
            "Home": 23484660,
            "HomeEarly": 23484660,
            "DifHours": 0,
            "Shift": "254"
        }
    },
    {
        "Person2": {
            "Op": "5703",
            "Name": "Persons name",
            "WorkHours": 12.25,
            "Start": " 7:45PM",
            "End": " 8:00AM",
            "Clock": false,
            "OFF": false,
            "ON": false,
            "OUT": false,
            "Late": 23484645,
            "Home": 23483940,
            "HomeEarly": 23483940,
            "DifHours": 0,
            "Shift": "251"
        }
    }

这是新格式

[
{
    "Op": "5709",
    "Name": "Persons name",
    "WorkHours": 5,
    "Start": " 3:00PM",
    "End": " 8:00PM",
    "Clock": false,
    "OFF": false,
    "ON": false,
    "OUT": false,
    "Late": 23484360,
    "Home": 23484660,
    "HomeEarly": 23484660,
    "DifHours": 0,
    "Shift": "254"
},
{
    "Op": "5703",
    "Name": "Persons name",
    "WorkHours": 12.25,
    "Start": " 7:45PM",
    "End": " 8:00AM",
    "Clock": false,
    "OFF": false,
    "ON": false,
    "OUT": false,
    "Late": 23484645,
    "Home": 23483940,
    "HomeEarly": 23483940,
    "DifHours": 0,
    "Shift": "251"
}

如何让JS / JQuery工作

2 个答案:

答案 0 :(得分:1)

我认为您可以简单地将数据作为字段处理,因为JSON之上没有其他声明:

 $.getJSON("People.json",
     function(data) {
         content = '<tr>';
         content += '<tbody>';
         for(var i = 0; i < data.length; i++) {
             var person = data[i]; 
             var op = person.Op; 
             var name = person.Name; 
             // etc...
         }
         ...

答案 1 :(得分:0)

我会编写一个简单的转换函数来获取现有数据并返回一个新的干净集:

function convert(data) {
  var people = data.People;
  var out = [];
  for (var i = 0, l = people.length; i < l; i++) {
    var person = people[i];
    var key = Object.keys(person);
    out.push(person[key]);
  }
  return out;
}

DEMO