Book Image

JavaScript JSON Cookbook

By : Ray Rischpater, Brian Ritchie, Ray Rischpater
Book Image

JavaScript JSON Cookbook

By: Ray Rischpater, Brian Ritchie, Ray Rischpater

Overview of this book

Table of Contents (17 chapters)
JavaScript JSON Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Reading and writing JSON in Perl


Perl predates JSON, although there's a good implementation of JSON conversion available from CPAN, the Comprehensive Perl Archive Network.

How to do it...

To begin with, download the JSON module from CPAN and install it. Typically, you'll download the file, unpack it, and then run the following code on a system that already has Perl and make configured:

perl Makefile.PL 
make 
make install

Here's a simple example:

use JSON;
use Data::Dumper;
my $json = '{ "call":"KF6GPE","type":"l","time":"1399371514",
"lasttime":"1418597513","lat": 37.17667,"lng": -122.14650,
"result" : "ok" }';
my %result = decode_json($json);
print Dumper(result);
print encode_json(%result);

Let's look at the interface the JSON module provides.

How it works...

The CPAN module defines the decode_json and encode_json methods to decode and encode JSON respectively. These methods interconvert between Perl objects, such as literal values and associative arrays, and strings containing JSON respectively.

The code begins by importing the JSON and Data::Dumper modules. Next, it defines a single string, $json, which contains the JSON we want to parse.

With the JSON in $json, we define %result to be the associative array containing the objects defined in the JSON, and dump the values in the hash on the next line.

Finally, we re-encode the hash as JSON and print the results to the terminal.

See also

For more information and to download the JSON CPAN module, visit https://metacpan.org/pod/JSON.