Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Charon's avatar

How to display json file in html table

My json file:

{"data":[{"index":"3","part":""}]},{"data":[{"index":"6","part":""}]},

And the javascript, getTasks() display the json file in table, but in json format, but i need show it in other column and other rows


async function getTasks(){
 const task = await request('GET', '/WebService/todo.json');
  document.getElementById("todoList").innerHTML=task
}
getTasks()
}


function addTodosToPage() {
 var table = document.getElementById("todoList");
 var tr = document.createElement("tr");
 var index = document.getElementById('index').value;
 var part = document.getElementById('part').value;
 tr.innerHTML = "<td>" + index + "</td><td>" + part + "</td>";
 table.appendChild(tr);


 todo_index++;


 tr.id = "todo-" + todo_index;

 var index = document.getElementById('index').value;
 var part = document.getElementById('part').value;

 tr.innerHTML = "\
 <td><input name='select-row' type='checkbox' value='" + todo_index + "'></td>\
 <td>" + index + "</td>\
 <td>" + part + "</td>\
 <td><button onclick='removeTodo(" + todo_index + ");'>x</button></td>";
 table.appendChild(tr);
}

function getFormData() {
   var index = document.getElementById("index").value;


   var part = document.getElementById("part").value;


   console.log("Index: " + index + " part: "+ part);
   var todoItem = new Todo(index, part);
   todos.push(todoItem);
   addTodosToPage(todoItem);
   saveTodoData();

}

HTML

<table class="table table-bordered table-striped">
  <thead>
    <tr>

      <th><input onchange="toggleSelection(this);" type='checkbox'></th>
      <th>Index</th>
      <th>Part</th>
      <th><button onclick='removeSelectedTodos();'>x</button></th>
    </tr>
  </thead>
  <tbody id="todoList">
  </tbody>
</table>
0 likes
2 replies
jlrdw's avatar

First

$data = json_decode($yourdata, true);

Pass to view and loop.

Will be associative and not object.

Charon's avatar

@jlrdw Ok, i add it to my php file, now the section with table looks like this

     $safe_json['data'][] = $safe_todo;
}
$json_decoded = json_decode($json_encoded, true);
foreach ($json_decoded as $i => $object)
    if ($object['data']['index'] == 1)
        unset($json_decoded[$i]);
// Zapis do pliku
$file = fopen( "todo.json", "a" ); 
//poprzenio fwrite( $file, '[' . json_encode( $safe_json ) . ']' ); 
fwrite( $file, json_encode( $safe_json, JSON_PRETTY_PRINT ) . ',' ); 
fclose( $file ); 

$data = file_get_contents('todo.json');


// decode json to associative array
$safe_json = json_decode($data, true);

What should i do next?

Please or to participate in this conversation.