使用jQuery将Dachser API嵌套JSON转换为HTML表格的问题排查
问题原因
- 数据源结构处理错误:你传入的
myList外层数组仅包含1个根对象,其中shipments字段是运单数组,根对象自身也属于一个独立运单,你没有先把所有运单条目统一提取到同一个数组中,导致仅遍历到1个外层元素,只生成1行数据。 - 未兼容嵌套字段:运单数据包含多层嵌套对象(如
forwarder、consignor、shipmentWeight等),原代码仅读取一级属性,无法解析嵌套结构,也无法生成对应的扁平表头。 - 未处理数组类型值:
names、streets、ssccs等数组类型的字段值,需要格式化为逗号分隔的字符串才能正常在表格中显示。
修复后可运行代码
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <style> th { font-weight: bold } </style> <body onLoad="buildHtmlTable()"> <table id="excelDataTable" border="1"> </table> </body>
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"}]}]}]; // 扁平化嵌套对象,处理数组类型字段 function flatten(obj, parentKey = '') { let result = {}; for (const key in obj) { if (obj.hasOwnProperty(key)) { const newKey = parentKey? `${parentKey}.${key}` : key; const value = obj[key]; if (typeof value === 'object' && value!== null &&!Array.isArray(value)) { Object.assign(result, flatten(value, newKey)); } else if (Array.isArray(value)) { result[newKey] = value.map(item => typeof item === 'object'? JSON.stringify(item) : item).join(', '); } else { result[newKey] = value?? ''; } } } return result; } // 从Dachser API返回的JSON中构建HTML表格 function buildHtmlTable() { // 提取所有运单数据:合并shipments数组内的运单 + 根对象自身的运单 const rootObj = myList[0]; const allShipments = [...rootObj.shipments]; // 提取根对象中除了shipments之外的属性作为单独运单 const rootShipment = Object.fromEntries(Object.entries(rootObj).filter(([key]) => key!== 'shipments')); if (Object.keys(rootShipment).length > 0) { allShipments.push(rootShipment); } // 所有运单扁平化处理 const flattenedShipments = allShipments.map(item => flatten(item)); const columns = addAllColumnHeaders(flattenedShipments); for (let i = 0; i < flattenedShipments.length; i++) { const row$ = $('<tr/>'); for (let colIndex = 0; colIndex < columns.length; colIndex++) { const cellValue = flattenedShipments[i][columns[colIndex]]?? ''; row$.append($('<td/>').html(cellValue)); } $("#excelDataTable").append(row$); } } // 生成表头,合并所有运单的字段作为表头 function addAllColumnHeaders(flattenedShipments) { const columnSet = []; const headerTr$ = $('<tr/>'); for (let i = 0; i < flattenedShipments.length; i++) { const rowHash = flattenedShipments[i]; for (const key in rowHash) { if ($.inArray(key, columnSet) == -1) { columnSet.push(key); headerTr$.append($('<th/>').html(key)); } } } $("#excelDataTable").append(headerTr$); return columnSet; }
内容的提问来源于stack exchange,提问作者cetipabo
相关产品推荐
相关产品推荐

