Software, your way.
How To Get Good Custom Software
(Download)
(PDF)
burger menu icon
WillMaster

WillMaster > LibraryWebsite Owner Tools

FREE! Coding tips, tricks, and treasures.

Possibilities weekly ezine

Get the weekly email website developers read:

 

Your email address

name@example.com
YES! Send Possibilities every week!

JSON Into HTML Table

JSON files can be annoying to read. It's doable. Just not the easiest thing to pursue.

More and more software can export JSON and read JSON exported by other software.

The PHP script that comes with this article converts JSON-encoded values into an HTML table — making the content of your JSON file easy to read. Just specify the location of the JSON file and click the button.

That's all there's to it.

What JSON Is

JSON is a plain text representation of pretty much any value that software uses. "Any value" includes arrays of values, the kind that can be converted into an HTML table.

As a comparison, a CSV file is also a representation of arrays of values. But JSON is much more versatile than a CSV file.

JSON can associate column names with arrays of values. Any line in a JSON file may have different column names and different types of values than other lines in the same file. Every line of a JSON file is complete by itself.

JSON has been gaining a huge amount of traction the last few years.

But this isn't an article evangelizing JSON. Instead, it's about software to read a JSON file and convert it into an HTML table.

How It Works

When the JSON-to-HTML script reads a line in the JSON file, it first determines whether or not the JSON represents an array of values. If not, the line is skipped, because only arrays of values are converted into the HTML table.

Next, it determines what the column names are. The column names are used to generate the headers of the HTML table.

Some types of arrays of values don't have column names. Those will have headers named in sequential numerical order starting with the number 0.

Probably most of your JSON files will always have the same column names for every row of values. But if your values are mixed, JSON-to-HTML can handle it.

As JSON-to-HTML scans the JSON file, it appends new column names it encounters to the right side of the current HTML table headers. (This is similar to how Master Form PHP works — when you add a field to an existing web page form, a new MySQL table column is automatically appended to the right side for storing the data received from the form field.)

When the HTML table headers have been composed, JSON-to-HTML publishes the associated values in table rows under the headers.

Every line of JSON in the file that represents an array of values becomes one row of the HTML table.

An illustration can make it more understandable.

The Illustration Values

Although your JSON files are likely to contain only one kind of array, this illustration will have both. It shows how JSON-to-HTML converts the two kinds when they're in one file.

One kind is arrays of values with column names and the other kind is arrays of values without column names.

Here are the values in plain text format so you can see what the data is supposed to be without having to read the JSON file.

Arrays of values with column names:

Names: Name       Fruit?
Value: Raspberry  Yes
Value: Potato     No
Value: Tomato     Yes
NameFruit?
RaspberryYes
PotatoNo
TomatoYes

Arrays of values without column names:

Value: Ice cream  Good company
Value: Coffee     Walking up
Ice creamGood company
CoffeeWaking up

The content of the JSON file:

This JSON file (well, pretend it's a file) has the above 5 arrays of values encoded, 3 with named columns and 2 without.

{"Name":"Raspberry","Fruit?":"Yes"}
{"Name":"Potato","Fruit?":"No"}
{"Name":"Tomato","Fruit?":"Yes"}
["Ice cream","Good company"]
["Coffee","Waking up"]

The above is fairly easy to read. More complex JSON encoding is less readable.

The converted HTML table:

This is the table JSON-to-HTML converts the above JSON file into.

NameFruit?01
RaspberryYes
PotatoNo
TomatoYes
Ice creamGood company
CoffeeWaking up

(If the table appears to be cut off, scroll or swipe horizontally to see the rest.)

As you can see, JSON-to-HTML converts JSON-encoded arrays of values into an HTML table. When there is more than one type of array of values, each kind get incorporated. Arrays embedded within arrays, however, will only product the word "Array" within the HTML table.

The JSON-to-HTML PHP Script

Note: This script is primitive. It will process only one level of values (no nesting) and every line of the table must be one line in the JSON file.

It is not suitable for prettified JSON or for nested JSON.

The script is copy and paste. No customization required.

<?php
/*
  JSON-to-HTML Table
  Version 1.0
  October 21, 2017

  Will Bontrager Software LLC
  https://www.willmaster.com/
  Copyright 2017 Will Bontrager Software LLC

  This software is provided "AS IS," without 
  any warranty of any kind, without even any 
  implied warranty such as merchantability 
  or fitness for a particular purpose.
  Will Bontrager Software LLC grants 
  you a royalty free license to use or 
  modify this software provided this 
  notice appears on all copies. 
*/

/* No customization required. */

$DisplayTable = isset($_POST['json']) and strlen(trim($_POST['json'])) ? true : false;
if( $DisplayTable )
{
  $LocationOfJSONfile = trim($_POST['json']);
  if( preg_match('!^/!',$LocationOfJSONfile) )
  {
    $LocationOfJSONfile = str_replace($_SERVER['DOCUMENT_ROOT'],'',$LocationOfJSONfile);
    $LocationOfJSONfile = "{$_SERVER['DOCUMENT_ROOT']}$LocationOfJSONfile";
  }
  $FileSize = file_exists($LocationOfJSONfile) ? filesize($LocationOfJSONfile) : false;
  $FirstLineIsHeader = isset($_POST['line1header']) ? true : false;
}
?><!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Quick JSON Display</title>
<style type="text/css">
html, body {
  font-size:100%; 
  font-family: verdana,arial,sans-serif;
  }

input[type="text"], input[type="submit"] {
  width:100%;
  font-size:1em;
  -moz-box-sizing:border-box; 
  -webkit-box-sizing:border-box; 
  box-sizing:border-box;
  }

input[type="text"] {
  border:1px solid #ccc;
  border-radius:3px; 
  padding:5px;
  }

th { font-size:80% line-height:110%; }
p, li, td { font-size:1em; line-height:120%; }
td { vertical-align:top;}
th { vertical-align:bottom; font-size:.8em; font-weight:bold; text-align:center; }
h1 { font-size:1.8em; line-height:100%; text-align:center; }
h2 { font-size:1.6em; }
h3 { font-size:1.4em; }
h4 { font-size:1.2em; }
h5 { font-size:1em; }
a { text-decoration:none; color:#1c5292; font-weight:bold; }
a, a img { border:none; outline:none; }
.content { position:relative; max-width:450px; margin:.5in auto; }
.tablediv { margin:.5in auto; display:table; }
.nowrap { white-space:nowrap; }
</style>
</head>
<body><div class="content"><div style="position:absolute; left:-5px; top:-10px;">
<a href="https://www.willmaster.com/">
<img src="https://www.willmaster.com/images/wmlogo_icon.gif" style="border:none; outline:none;">
</a>
</div>
<h1 style="margin:0 0 0 50px;">JSON-to-HTML Table</h1>

<div style="height:45px;"></div>

<?php if($DisplayTable): ?>
<?php if( ! $FileSize): ?>
<p><b>Sorry, but I'm unable to find file <?php echo($_POST['json']); ?>.</b></p>
<?php else: ?>

</div>
<div class="tablediv"><table border="1" cellpadding="7" cellspacing="0" style="border-collapse:collapse;">
<?php
$numCols = 0;
$columns = array();
$columntrack = array();
foreach( file($LocationOfJSONfile) as $line )
{
  $line = trim($line);
  $th = json_decode($line,true);
  if( ! is_array($th) ) { continue; }
  foreach( $th as $column => $text )
  {
    if( isset($columntrack[$column]) ) { continue; }
    $columntrack[$column] = count($columns);
    $columns[] = $column;
  }
}
$numCols = count($columns);
echo "\n<tr>";
foreach( $columns as $col ) { echo "<th>$col</th>"; }
echo "\n</tr>";
foreach( file($LocationOfJSONfile) as $line )
{
  $cols = array();
  for( $i=0; $i<$numCols; $i++ ) { $cols[$i] =''; }
  $line = trim($line);
  $th = json_decode($line,true);
  if( ! is_array($th) ) { continue; }
  foreach( $th as $column => $text )
  {
    echo "\n<tr>";
    $cols[$columntrack[$column]] = $text;
    echo "\n</tr>";
  }
  foreach( $cols as $col ) { echo "<td>$col</td>"; }
}
?>
</table></div><div class="content">
<p style="margin-top:45px;">
Display another?
</p>
<?php endif; ?>
<?php endif; ?>

<form method="post" enctype="multipart/form-data" action="<?php echo(htmlspecialchars($_SERVER['PHP_SELF'])); ?>">
<p>
Server location of JSON file to display.<br>
<input type="text" name="json">
</p>
<p>
<input type="submit" value="Convert JSON to HTML Table">
</p>
</form>
<p style="margin-top:45px;">
Copyright 2017 <a href="https://www.willmaster.com/"><span class="nowrap">Will Bontrager</span> <span class="nowrap">Software LLC</span></a>
</p>
</div>
</body>
</html>

Copy the above code above for the JSON-to-HTML PHP script and save it as a plain text file to your hard drive.

Name the file JtoH.php or whatever name you prefer (needs .php file name extension).

Upload JtoH.php to your server.

Using JSON-to-HTML

Type the URL of JtoH.php into your browser's address bar. You'll see the dashboard.

screenshot of dashboard

Specify the server location of the JSON file. (The JSON file needs to be on the server.)

Click the "Convert JSON to HTML Table" button.

That's all :)

The JSON data is converted into an HTML table and displayed in your browser.

Adding Functionality

Custom functionality can be added to the JSON-to-HTML software. Ideas include:

  • Have the option to grab the JSON from the internet with a regular http://... URL instead of specifying a file location on the server.

  • Have a multi-line text box in the control panel where the content JSON file can be pasted in.

  • Have the option to upload the JSON file for converting into an HTML table.

  • Launch JtoH.php with a link to convert on demand, something like http://example.com/JtoH.php?file.json (instead of going through the control panel). The link URL could be published in PDFs, email, and in web pages.

  • Insert the converted JSON values into an HTML table live, when the web page loads — so the table has the latest information.

Contact us to inquire about any custom functionality you want.

(This article first appeared in Possibilities newsletter.)

Will Bontrager

Was this article helpful to you?
(anonymous form)

Support This Website

Some of our support is from people like you who see the value of all that's offered for FREE at this website.

"Yes, let me contribute."

Amount (USD):

Tap to Choose
Contribution
Method

All information in WillMaster Library articles is presented AS-IS.

We only suggest and recommend what we believe is of value. As remuneration for the time and research involved to provide quality links, we generally use affiliate links when we can. Whenever we link to something not our own, you should assume they are affiliate links or that we benefit in some way.

How Can We Help You? balloons
How Can We Help You?
bullet Custom Programming
bullet Ready-Made Software
bullet Technical Support
bullet Possibilities Newsletter
bullet Website "How-To" Info
bullet Useful Information List

© 1998-2001 William and Mari Bontrager
© 2001-2011 Bontrager Connection, LLC
© 2011-2024 Will Bontrager Software LLC