-2

I have a JSON coming from the Dachser API service, sometimes there are more or less fields. I tried to adapt a piece of code posted on Stack Overflow but I can't find why it doesn't build the table.

The result should be a table header and as many rows as shipments (3 in my example).The online service here does it as expected. The resulting table is not nested, you get 3 rows.

I don't know how they do but it's what I'm trying get with my code.

Actually, I'm getting just 1 cell. My code:

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>

2
  • why it doesn't build the table - because your top level array has only one item "shipments" and your "addAllColumnHeaders" doesn't attempt any recursion / nesting (and no, I'm not going to build it for you, just providing a reason to your question) Commented Oct 29, 2021 at 14:10
  • unfortunately no, i tried all the solutions in this topic, none are working with my JSONs. Commented Oct 29, 2021 at 15:02

1 Answer 1

1

Example for advanced JSON objects to HTML tables with jQuery:

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>

Reference:

Sign up to request clarification or add additional context in comments.

1 Comment

This is close but the output here is a nested table. what i'm trying to get is a table like this: i.imgur.com/wmYnMZ8.png so we need to create non nested columns.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.