【问题标题】:Convert nested JSON into HTML table with jQuery [duplicate]使用 jQuery 将嵌套的 JSON 转换为 HTML 表 [重复]
【发布时间】:2021-12-14 14:31:05
【问题描述】:

我有一个来自 Dachser API 服务的 JSON,有时会有或多或少的字段。我试图修改发布在 Stack Overflow 上的一段代码,但我找不到它为什么不建表的原因。

结果应该是一个表头和与出货量一样多的行(在我的示例中为 3)。在线服务here 按预期执行。结果表没有嵌套,你得到 3 行。

我不知道他们是怎么做的,但这是我试图用我的代码得到的。

实际上,我只得到了 1 个单元格。我的代码:

var myList = [{
  "shipments": [{
    "id": "4390906456",
    "shipmentDate": "2021-10-29",
    "forwarder": {
      "id": "60",
      "partnerGLN": "5990034733003",
      "names": ["LIEGL & DACHSER KFT."],
      "addressInformation": {
        "city": "Pilisvörösvár",
        "postalCode": "2085",
        "countryCode": "HU"
      }
    },
    "shipmentWeight": {
      "weight": 818.32,
      "unit": "kg"
    },
    "consignor": {
      "id": "21269784",
      "partnerGLN": "8340338594266",
      "names": ["Daisy Duck"],
      "addressInformation": {
        "streets": ["Boulevard de Parc 12"],
        "city": "Coupvray",
        "postalCode": "77700",
        "countryCode": "FR"
      }
    },
    "consignee": {
      "id": "21946026",
      "partnerGLN": "1290415437220",
      "names": ["Lucky Luke"],
      "addressInformation": {
        "streets": ["Hot Stone Highway 47"],
        "city": "Texas City",
        "postalCode": "77590",
        "countryCode": "US"
      }
    },
    "ssccs": ["00335958250088747255"],
    "references": [{
      "code": "003",
      "value": "FLirSXddJh"
    }, {
      "code": "007",
      "value": "AMA0t1Lvhu"
    }, {
      "code": "SN",
      "value": "4390906456"
    }],
    "status": [{
      "statusSequence": 1,
      "id": "68596368804",
      "statusDate": "2021-10-26T11:33:00",
      "eventSetter": {
        "id": "250",
        "partnerGLN": "4046823000007",
        "names": ["DACHSER Denmark A/S Logistics Centre Copenhagen"],
        "addressInformation": {
          "city": "Hvidovre",
          "postalCode": "2650",
          "countryCode": "DK"
        }
      },
      "event": {
        "code": "A",
        "extendedCode": "",
        "description": "Expédié vers le terminal"
      },
      "ssccs": ["00335958250088747255"]
    }]
  }, {
    "id": "A6761334450979547136",
    "shipmentDate": "2021-10-28",
    "forwarder": {
      "id": "60",
      "partnerGLN": "5990034733003",
      "names": ["LIEGL & DACHSER KFT."],
      "addressInformation": {
        "city": "Pilisvörösvár",
        "postalCode": "2085",
        "countryCode": "HU"
      }
    },
    "shipmentWeight": {
      "weight": 783.8,
      "unit": "kg"
    },
    "portOfDeparture": "MUC",
    "portOfDestination": "MUC",
    "consignor": {
      "id": "68779302",
      "partnerGLN": "8588788490809",
      "names": ["Ernie & Bert"],
      "addressInformation": {
        "streets": ["Sesamstraße 9b"],
        "city": "Köln",
        "postalCode": "50997",
        "countryCode": "DE"
      }
    },
    "consignee": {
      "id": "58236212",
      "partnerGLN": "8468915205577",
      "names": ["Sams c/o Taschenbier"],
      "addressInformation": {
        "streets": ["Bavariafilmpl. 7"],
        "city": "Grünwald",
        "postalCode": "82031",
        "countryCode": "DE"
      }
    },
    "references": [{
      "code": "003",
      "value": "NNUTgJiCZC"
    }, {
      "code": "007",
      "value": "I9KsBaXzjk"
    }, {
      "code": "HAW",
      "value": "UuR67226426"
    }],
    "status": [{
      "statusSequence": 1,
      "id": "50475790203",
      "statusDate": "2021-10-26T11:33:00",
      "eventSetter": {
        "id": "6",
        "partnerGLN": "4022128000003",
        "names": ["DACHSER SE Logistikzentrum Allgäu"],
        "addressInformation": {
          "city": "Memmingen",
          "postalCode": "87700",
          "countryCode": "DE"
        }
      },
      "event": {
        "code": "Z",
        "extendedCode": "",
        "description": "Livré conforme"
      },
      "signorOfTheProofOfDelivery": "TASCHENBIER"
    }]
  }]
}];

// Builds the HTML Table out of myList json data from DACHSER API service.
function buildHtmlTable() {
  var columns = addAllColumnHeaders(myList);

  for (var i = 0; i < myList.length; i++) {
    var row$ = $('<tr/>');
    for (var colIndex = 0; colIndex < columns.length; colIndex++) {
      var cellValue = myList[i][columns[colIndex]];

      if (cellValue == null) {
        cellValue = "";
      }

      row$.append($('<td/>').html(cellValue));
    }
    $("#excelDataTable").append(row$);
  }
}

// Adds a header row to the table and returns the set of columns.
// Need to do union of keys from all records as some records may not contain
// all records
function addAllColumnHeaders(myList) {
  var columnSet = [];
  var headerTr$ = $('<tr/>');

  for (var i = 0; i < myList.length; i++) {
    var rowHash = myList[i];
    for (var key in rowHash) {
      if ($.inArray(key, columnSet) == -1) {
        columnSet.push(key);
        headerTr$.append($('<th/>').html(key));
      }
    }
  }
  $("#excelDataTable").append(headerTr$);

  return columnSet;
}
th {
  font-weight: bold
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<body onLoad="buildHtmlTable()">
  <table id="excelDataTable" border="1">
  </table>
</body>

【问题讨论】:

  • 为什么不建表 - 因为您的顶级数组只有一项“shipments”,而您的“addAllColumnHeaders”不会尝试任何递归/嵌套(不,我不会为你构建它,只是为你的问题提供一个理由)
  • 很遗憾,没有,我尝试了本主题中的所有解决方案,但没有一个适用于我的 JSON。

标签: javascript html jquery json


【解决方案1】:

使用 jQuery 将高级 JSON 对象转换为 HTML 表的示例:

var myList = [{
  "shipments": [{
    "id": "4390906456",
    "shipmentDate": "2021-10-29",
    "forwarder": {
      "id": "60",
      "partnerGLN": "5990034733003",
      "names": ["LIEGL & DACHSER KFT."],
      "addressInformation": {
        "city": "Pilisvörösvár",
        "postalCode": "2085",
        "countryCode": "HU"
      }
    },
    "shipmentWeight": {
      "weight": 818.32,
      "unit": "kg"
    },
    "consignor": {
      "id": "21269784",
      "partnerGLN": "8340338594266",
      "names": ["Daisy Duck"],
      "addressInformation": {
        "streets": ["Boulevard de Parc 12"],
        "city": "Coupvray",
        "postalCode": "77700",
        "countryCode": "FR"
      }
    },
    "consignee": {
      "id": "21946026",
      "partnerGLN": "1290415437220",
      "names": ["Lucky Luke"],
      "addressInformation": {
        "streets": ["Hot Stone Highway 47"],
        "city": "Texas City",
        "postalCode": "77590",
        "countryCode": "US"
      }
    },
    "ssccs": ["00335958250088747255"],
    "references": [{
      "code": "003",
      "value": "FLirSXddJh"
    }, {
      "code": "007",
      "value": "AMA0t1Lvhu"
    }, {
      "code": "SN",
      "value": "4390906456"
    }],
    "status": [{
      "statusSequence": 1,
      "id": "68596368804",
      "statusDate": "2021-10-26T11:33:00",
      "eventSetter": {
        "id": "250",
        "partnerGLN": "4046823000007",
        "names": ["DACHSER Denmark A/S Logistics Centre Copenhagen"],
        "addressInformation": {
          "city": "Hvidovre",
          "postalCode": "2650",
          "countryCode": "DK"
        }
      },
      "event": {
        "code": "A",
        "extendedCode": "",
        "description": "Expédié vers le terminal"
      },
      "ssccs": ["00335958250088747255"]
    }]
  }, {
    "id": "A6761334450979547136",
    "shipmentDate": "2021-10-28",
    "forwarder": {
      "id": "60",
      "partnerGLN": "5990034733003",
      "names": ["LIEGL & DACHSER KFT."],
      "addressInformation": {
        "city": "Pilisvörösvár",
        "postalCode": "2085",
        "countryCode": "HU"
      }
    },
    "shipmentWeight": {
      "weight": 783.8,
      "unit": "kg"
    },
    "portOfDeparture": "MUC",
    "portOfDestination": "MUC",
    "consignor": {
      "id": "68779302",
      "partnerGLN": "8588788490809",
      "names": ["Ernie & Bert"],
      "addressInformation": {
        "streets": ["Sesamstraße 9b"],
        "city": "Köln",
        "postalCode": "50997",
        "countryCode": "DE"
      }
    },
    "consignee": {
      "id": "58236212",
      "partnerGLN": "8468915205577",
      "names": ["Sams c/o Taschenbier"],
      "addressInformation": {
        "streets": ["Bavariafilmpl. 7"],
        "city": "Grünwald",
        "postalCode": "82031",
        "countryCode": "DE"
      }
    },
    "references": [{
      "code": "003",
      "value": "NNUTgJiCZC"
    }, {
      "code": "007",
      "value": "I9KsBaXzjk"
    }, {
      "code": "HAW",
      "value": "UuR67226426"
    }],
    "status": [{
      "statusSequence": 1,
      "id": "50475790203",
      "statusDate": "2021-10-26T11:33:00",
      "eventSetter": {
        "id": "6",
        "partnerGLN": "4022128000003",
        "names": ["DACHSER SE Logistikzentrum Allgäu"],
        "addressInformation": {
          "city": "Memmingen",
          "postalCode": "87700",
          "countryCode": "DE"
        }
      },
      "event": {
        "code": "Z",
        "extendedCode": "",
        "description": "Livré conforme"
      },
      "signorOfTheProofOfDelivery": "TASCHENBIER"
    }]
  }]
}];

// Builds the HTML Table out of myList json data from Ivy restful service.
function buildHtmlTable() {
  addTable(myList, $("#excelDataTable"));
}

function addTable(list, appendObj) {
  var columns = addAllColumnHeaders(list, appendObj);
  for (var i = 0; i < list.length; i++) {
    var row$ = $('<tr/>');
    for (var colIndex = 0; colIndex < columns.length; colIndex++) {
      var cellValue = list[i][columns[colIndex]];

      if (cellValue == null) {
        cellValue = "";
      }

      if (cellValue.constructor === Array) {
        $a = $('<td/>');
        row$.append($a);
        addTable(cellValue, $a);

      } else if (cellValue.constructor === Object) {

        var array = $.map(cellValue, function(value, index) {
          return [value];
        });

        $a = $('<td/>');
        row$.append($a);
        addObject(array, $a);

      } else {
        row$.append($('<td/>').html(cellValue));
      }
    }
    appendObj.append(row$);
  }
}


function addObject(list, appendObj) {
  for (var i = 0; i < list.length; i++) {
    var row$ = $('<tr/>');

    var cellValue = list[i];

    if (cellValue == null) {
      cellValue = "";
    }

    if (cellValue.constructor === Array) {
      $a = $('<td/>');
      row$.append($a);
      addTable(cellValue, $a);

    } else if (cellValue.constructor === Object) {

      var array = $.map(cellValue, function(value, index) {
        return [value];
      });

      $a = $('<td/>');
      row$.append($a);
      addObject(array, $a);

    } else {
      row$.append($('<td/>').html(cellValue));
    }
    appendObj.append(row$);
  }
}

// Adds a header row to the table and returns the set of columns.
// Need to do union of keys from all records as some records may not contain
// all records
function addAllColumnHeaders(list, appendObj) {
  var columnSet = [];
  var headerTr$ = $('<tr/>');

  for (var i = 0; i < list.length; i++) {
    var rowHash = list[i];
    for (var key in rowHash) {
      if ($.inArray(key, columnSet) == -1) {
        columnSet.push(key);
        headerTr$.append($('<th/>').html(key));
      }
    }
  }
  appendObj.append(headerTr$);

  return columnSet;
}
th {
  font-weight: bold
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<body onload="buildHtmlTable()">
  <table id="excelDataTable" border="1">
  </table>
</body>

参考:

【讨论】:

  • 这很接近,但这里的输出是一个嵌套表。我想要得到的是这样的表:i.imgur.com/wmYnMZ8.png 所以我们需要创建非嵌套列。
猜你喜欢
  • 2010-11-15
  • 1970-01-01
  • 1970-01-01
  • 2019-07-04
  • 2012-12-28
  • 2021-06-09
  • 2021-08-26
  • 1970-01-01
相关资源
最近更新 更多