And Now For Some Really Basic Perl - JSON Manipulation

And Now For Some Really Basic Perl - JSON Manipulation

In PerlWorld, there are basically two ways of doing virtually anything.
a) Do it yourself
b) Go look at CPAN and realize that Someone Has Done It Better
Being a card-carrying member of approach (b) above, here's a remarkably simple way of mainpulating JSON in PerlWorld

First, for some code based on Marc Lehmann's truly excellent JSON module

# Include the JSON module
use JSON::XS;

# Create a thing (called $json) that will be used to encode JSON strings
$json = JSON::XS->new();
# Make sure that the resultant JSON will print out all nice and pretty
$json->pretty(1);

# Create a basic JSON hash
$jsonStructure->{id} = "1234";
$jsonStructure->{method} = "ReallyCoolMethod";
$jsonStructure->{version} = "1.0.1";

# $prettyJSON will contain the text string which is the Oh-So-Pretty version of $jsonStructure
$prettyJson = $json->encode($jsonStructure);


If you printed out the contents of $prettyJson, you'd get the following
{
"version" : "1.0.1",
"method" : "ReallyCoolMethod",
"id" : "1234"
}

Likewise, if you just reverse the above process, i.e.,
$jsonStructure = $json->encode($prettyJson);
then you take a piece of JSON and convert it into a nice perl data structure.

Pretty trivial, isn't it?

Incidentally
1) Do note that the above is to make a point, and I've avoided so much that would go into making it Good. For example
a) using my --> my $json = JSON::XS->new();
b) using eval to trap errors
eval {
$prettyJson = $json->encode($jsonStructure);
};
if ($@) {
...some stuff here...
}

2) If you eliminate
$json->pretty(1);
above, you'll end up with output that looks like
{"version":"1.0.1","method":"ReallyCoolMethod","id":"1234"}

See the value of being pretty?

Comments

Popular posts from this blog

Cannonball Tree!

Erlang, Binaries, and Garbage Collection (Sigh)

Visualizing Prime Numbers