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

Hi, i am fetching results from mysql DB and want to get a proper json output. with JSON:PP encode_json function i get the below output

use JSON::PP; my $json = JSON::PP->new; my $json_output=encode_json( { JSON1=> \@my_A } ); print $json_output;

output is

{"JSON1":["{\"name\":\"Name 1\",\"myArray\":[1,2,3]}","{\"name\":\"Nam +e 2\",\"myArray\":[4,0,0]}","{\"name\":\"Name 3\",\"myArray\":[5,0,6] +}"]}

but my JS script think the below format is the correct one

{"JSON1":[{"name":"Name 1","myArray":[1,2,3]},{"name":"Name 2","myArra +y":[4,0,0]},{"name":"Name 3","myArray":[5,0,6]}]}

without the additional \ and ". Any help please?

Replies are listed 'Best First'.
Re: perl-json format
by moritz (Cardinal) on Apr 18, 2012 at 06:23 UTC

    It seems that @my_A contains a string which is already JSON-encoded. Passing it to encode_json double-encodes it, ie escapes all quotes with backslashes.

    If that is the case, you can produce your desired result through a simple text operation, like

    my $json_output = '{"JSON1:[" . join(',', @my_A) .']}';

    of you have to decode the existing JSON string before inserting it into a data structure that you pass to encode_json.

      Thanks for all the replies. Yes, @my_A is a JSON string itself constructed with the mysql rows results and my $json_output=encode_json( { JSON1=> \@my_A } ); is encoding again and hence the issue of extra \ and ".
Re: perl-json format
by zwon (Abbot) on Apr 18, 2012 at 06:21 UTC
    I guess @my_A contains a single value that is json encoded array. You should decode it before use.
Re: perl-json format (data)
by tye (Sage) on Apr 18, 2012 at 06:13 UTC

    If @my_A were to contain references to three hashes, then the latter output would be expected.

    Since you don't show even a hint at how @my_A is being populated, by far the simplest explanation is that @my_A does not contain references to three hashes but contains a single string and that this string contains how JSON would represent an array containing references to three hashes.

    - tye