i want to create a json viewer for an api that converts a json to a list of table, can someone point me how its done? i know its possible but i don’t know how to do it.
e.g.
{"name":diana,
"age":12,
"gender":"male"}
to:
<table>
<tr>
<td>name:</td><td>diana</td>
</tr>
<tr>
<td>age:</td><td>12</td>
</tr>
<tr>
<td>gender:</td><td>male</td>
</tr>
</table>
if something is not clear please let me know :) i forgot to mention that i will be working for a nested json. m(_ _)m
Use json_decode
to parse json, then iterate over the result...
echo "<table>\n";
$data = json_decode($json, true);
foreach($data as $key=>$value) echo "<tr><td>{$key}:</td><td>{$value}</td></tr>\n";
echo "</table>\n";
Note that this will work only for such "simple" json objects as you gave in example...
If theres multi-level nesting, this won't be enough. You will have to check the type of $value
and decide how to print it at any level of nesting...
Also note, that json string can also be not an object at all. It can also be a primitive type.
Ultimately, you either have a multidimensional array, or an object (if you ommit the second parameter from json_decode
call). From that point on, the 'goal' changes from pretty-print a json object into pretty-print a php variable. There are plenty of solutions for that.