in reply to understanding json in perl

Looking at your code, first of all you only need the decode_json() statement if you have a value provided to you in JSON format. If not, then you can start with a familiar perl data structure, and use the encode_json() statement to convert it to something to be passed elsewhere. Here is a short example:

use strict; use warnings; use Data::Dumper; use JSON; my $ds = { }; # Show that $ds is an empty hashref. print Data::Dumper->Dump( [ \$ds, ], [ qw( *ds ) ], ), qq{\n}; $ds->{trans2}[0] = 90; push @{$ds->{trans2}}, 20; # Show that element 'trans2' of $ds now points to a 2-element array. print Data::Dumper->Dump( [ \$ds, ], [ qw( *ds ) ], ), qq{\n}; # Loop through the structure and print all elements. foreach my $k ( sort { $a cmp $b } keys %{$ds} ) { print qq{\t}, $k, qq{\t=>\n}; foreach my $i ( 0 .. $#{$ds->{$k}} ) { print qq{\t} x 2, qq{[$i]\t=>\t}, $ds->{$k}[$i], qq{\n}; } } # Encode in JSON format for transmission my $eson = encode_json( $ds ); print $eson, qq{\n}; # Decode from JSON format, for verification my $nson = decode_json( $eson ); print Data::Dumper->Dump( [ \$nson, ], [ qw( *nson ) ] ), qq{\n};

Hope that helps.

Replies are listed 'Best First'.
Re^2: understanding json in perl
by sanjeevbinf (Initiate) on Apr 27, 2014 at 05:19 UTC
    @atcroft Thank you for you the code. I needed the output like the encode one. Now I get the hold of it. Shall work on it.

    @ NetWallah , sundialsvc4- Thank you for the replies.