Convert JSON to HTML with JSON::Parse and HTML::Make

This example Perl script demonstrates converting arbitrary JSON to HTML using JSON::Parse and HTML::Make.

#!/home/ben/software/install/bin/perl
use warnings;
use strict;
use utf8;
use JSON::Parse 'parse_json';
use HTML::Make;
binmode STDOUT, ":encoding(utf8)";
my $json =<<EOF;
{"words":[{"j_pron_only":"パイプ","word":"pipe"},{"word":"cutting","j_pron_only":"カティング"},{"word":"implement","j_pron_only":"インプリムント"}]}
EOF
my $p = parse_json ($json);
my $html = json_to_html ($p);
print $html->text ();
exit;

sub json_to_html
{
    my ($input) = @_;
    my $element;
    if (ref $input eq 'ARRAY') {
        $element = HTML::Make->new ('ol');
        for my $k (@$input) {
            my $li = $element->push ('li');
            $li->push (json_to_html ($k));
        }
    }
    elsif (ref $input eq 'HASH') {
        $element = HTML::Make->new ('table');
        for my $k (sort keys %$input) {
            my $tr = $element->push ('tr');
            $tr->push ('th', text => $k);
            my $td = $tr->push ('td');
            $td->push (json_to_html ($input->{$k}));
        }
    }
    else {
        $element = HTML::Make->new ('span', text => $input);
    }
    return $element;
}

(download)

As HTML, the output looks like this:

words
  1. j_pron_only パイプ
    word pipe
  2. j_pron_only カティング
    word cutting
  3. j_pron_only インプリムント
    word implement

The HTML output looks like this:

<table>
<tr>
<th>words</th>
<td><ol>
<li><table>
<tr>
<th>j_pron_only</th>
<td><span>パイプ</span>
</td>
</tr>
<tr>
<th>word</th>
<td><span>pipe</span>
</td>
</tr>
</table>
</li>
<li><table>
<tr>
<th>j_pron_only</th>
<td><span>カティング</span>
</td>
</tr>
<tr>
<th>word</th>
<td><span>cutting</span>
</td>
</tr>
</table>
</li>
<li><table>
<tr>
<th>j_pron_only</th>
<td><span>インプリムント</span>
</td>
</tr>
<tr>
<th>word</th>
<td><span>implement</span>
</td>
</tr>
</table>
</li>
</ol>
</td>
</tr>
</table>


Copyright © Ben Bullock 2009-2023. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (benkasminbullock@gmail.com) or use the discussion group at Google Groups. / Privacy / Disclaimer