Create HTML from JSON in Perl

#!/usr/bin/perl

use strict;
use warnings;
use utf8;
use JSON;
use autodie;
use HTML::TreeBuilder;

my $string;
{
    local $/;
    open my $fh1,"<files.json" or die "open failed <files.json>: $!\n";
    $string = <$fh1>;
    close $fh1 or die "close failed <files.json>: $!\n";
}

# Parse JSON in PERL
my $data = decode_json($string);

# Initialize HTML
my $html = "<html><head><title>JSON Viewer</title></head><body><table border=\"1\"><thead><tr><th width=\"300\">Keys</th><th width=\"500\">Values</th></tr></thead><tbody>";

# Update HTML
foreach my $key (keys(%$data))
{
    $html = $html."<tr><td>".$key."</td><td>";
    my $values = $data->{$key};
    foreach my $value (@{$values})
    {
        $html = $html.$value."<br/>";
    }
    $html = $html."</td></tr>";
}
   
# Generate HTML
$html = $html."</tbody></table></body></html>";
my $h = HTML::TreeBuilder->new_from_content($html);
open my $fh2,">files.html" or die "open failed <files.html>: $!\n";
print $fh2 $h->as_HTML('',"\t") or die "print failed <files.html>: $!\n";
close $fh2 or die "close failed <files.html>: $!\n";

This Perl script reads a JSON file and builds HTML from it, using the JSON module to parse the data and HTML::TreeBuilder to construct the markup. It is the reverse of turning HTML into JSON.

Generating HTML from structured data is the basis of simple reporting and templating, where the data lives as JSON and the presentation is produced on demand.

Comments

Popular posts from this blog

[Solved] Error: No such keg: /usr/local/Cellar/gcc

[How To] Unfollow Non-followers on Instagram