Scott Penrose

JSON

Scott is an expert software developer with over 30 years experience, specialising in education, automation and remote data.

So I am stuck in the car, no internet connection, and I forgot to install the CPAN module JSON -- Damn!

So I wrote up a quick and dirty one, that shows an example of nice formatting and recursive function.

NEVER USE THIS

Use JSON that is what it is for.

#!Perl
sub to_json {
    my ($in, $level) = @_;
    my $out;
    if (ref($in) eq "HASH") {
        $out .= "{\n";
        $out .= join(",\n", map { "\t"x$level . "$_: " . to_json($in->{$_}, $level + 1) } keys %$in);
        $out .= "\n" . "\t"x($level-1) . "}\n";
    }
    elsif (ref($in) eq "ARRAY") {
        $out .= "[\n";
        $out .= join(",\n", map { to_json($_, $level + 1) } @$in);
        $out .= "\t"x($level-1) . "]\n";
    }
    elsif (ref($in)) {
        die "Sorry " . ref($in) . " not supported";
    }
    else {
        $out .= qq{"$in"};
    }
    return $out;
}

Content Type

The choices:

  • application/x-javascript
  • application/jsonrequest
  • application/json
  • application/x-json
  • text/x-json
  • text/json
  • app/x-json

But finally IANA has officially registered a MIME type for JSON: application/json.

  • PHP: header("Content-type: application/json");
  • Perl: print header(-type => 'application/json');
  • Most anything else: print "Content-type: application/json\r\n";

  • Javascript
  • Perl