Bits & Bytes #4 - And Now For Some Really Basic Perl - JSON Manipulation

This is the 4th in our ongoing Bits and Bytes Series by Aptela's CTO Mahesh Paolini-Subramanya. WARNING: tech-speak ahead...

Here, at Aptela, we tend to use Perl as the glue that binds virtually everything together.  Herewith one small example of using perl to manipulate JSON - remember, JSON is the data format that we use for moving information across virtually all the domains in Aptela 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->1.6.4 = "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?

Posted in: VOIP on Aug 24, 2009 by Mahesh Paolini-Subramanya. |

Bookmark and Share

About the Author

Mahesh Paolini-Subramanya is the Chief Technology Officer (CTO) at Aptela. Since 2001, Mr. Paolini-Subramanya has been responsible for Aptela's technical vision, development and implementation. Drawing upon 20 years of accomplishments in telecommunications, Mr. Paolini-Subramanya is a recognized thought leader in the Voice over Internet Protocol (VoIP) industry and in Cloud Computing. More from this author >

Comments

hooooooooooooooooooooola

thankssssss

Great post, but I think that you meant

$jsonStructure = $json->decode($prettyJson);

below this statement “Likewise, if you just reverse the above process, i.e.”

Post a Comment