Output a table from a JSON file

I have a JSON file and am trying to input the values into a table
Can I do this like…

var content = file_get_contents("data/ac.json");

//use a template literal to create a table
document.getElementById("myData").innerHTML = `
<table>
<caption>Units: ${data.length}</caption>
<thead>
<tr>
<th>Name</th> 
<th>Width</th>
</tr>
</thead>
<tbody>
${contents.map(function(data) {
 <tr> 
<td>{data.name}</td>
<td>{data.width}</td>
<tr>
}).join('')}
</tbody>
</table>

`

Hi @lurtnowski, everything inside the ${...} is getting evaluated as JS code, and this is not valid syntax; you’ll have to return another template string here:

contents.map(function(data) {
  return `
   <tr> 
      <td>${data.name}</td>
      <td>${data.width}</td>
    <tr>
  `
}).join('')
1 Like

am getting
Uncaught SyntaxError: Unexpected token ‘<’
on

<script>
const content = <?=file_get_contents("data/cooling-areas.json")?>;

document.getElementById("myTable").innerHTML = `
<table class="table table-bordered shadow-sm">
<caption>Count: ${content.length}
<thead><tr><th>Name</th><th>Cooling Area</th></tr></thead>
<tbody>
content.map(function(unit) {
  return `
   <tr> 
      <td>${unit.Name}</td>
      <td>${unit.Cooling_Area}</td>
   </tr>
  `
}).join('')
</tbody>
</table>
`
</script>

The error goes away if I comment out the stuff inside <tbody>
I dont see a syntax error
image

The outer JS expression must also be wrapped in ${...}.

1 Like