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.


In reply to Re: understanding json in perl by atcroft
in thread understanding json in perl by sanjeevbinf

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.