perlpreben has asked for the wisdom of the Perl Monks concerning the following question:

Hi, im using the JSON module, with the following code:

my %customers; my $customer_ref = \%customers; $customers{'cust'}{'id'} = $id; $customers{'cust'}{'name'} = $name; my $json = encode_json $customers_ref; print $json;

The output is as follow:

{"cust":{"name":"Johns Autoshop","id":"5"}}

But as far as I am able to figure out, only:

{"cust":[{"name":"Johns Autoshop","id":"5"}]}

..is valid for Jquery. So how can I add the [ and ] characters? Didnt find anything in the docs that descibed this problem.

Replies are listed 'Best First'.
Re: How to output proper JSON
by muba (Priest) on Dec 14, 2011 at 23:40 UTC

    The output is correct. $customers{'cust'} contains a (reference to a) hash with the keys "id" and "name". The encode_json output shows precisely that.

    So if you want your result to be a map containing an array containing a map, you'd have to alter your original data structure to represent that. Instead of having $customers{'cust'} contain a hashref, have it contain an arrayref instead.

    # I didn't test the code, but I suspect this should give you what you +want. $customers{'cust'} = [ { id => $id, name => $name, } ];
      Ahhhhh! Thanks. Works perfect!!