JSON formatting in Perl

I am trying to create a JSON object that displays maps associated with a specific user, but never worked with nested JSON objects. This is what I want:

{ "success":"list of users maps", "maps":[ { "id":"1", "name":"Home to LE", "date_created":"1366559121" }, { "id":"2", "name":"Test 1", "date_created":"1366735066" } ] } 

with this perl code:

  my $maps = []; for (my $x = 0; $x < $sth->rows; $x++) { my ($id, $name, $date) = $sth->fetchrow_array(); my $map = qq{{"id":"$id","name":"$name","date_created":"$date"}}; push $maps, $map; } my $j = JSON::XS->new->utf8; my $output = $j->encode({ "success"=>"list of users maps", "maps"=>$maps }); 

But the conclusion I get is:

 { "success":"list of users maps", "maps":[ "{\"id\":\"1\",\"name\":\"Home to LE\",\"date_created\":\"1366559121\"}", "{\"id\":\"2\",\"name\":\"Test 1\",\"date_created\":\"1366735066\"}" ] } 

Therefore, when I process it in my Javascript, data.maps [x] .id is undefined. I am sure that the JSON output is incorrectly formatted.

Can someone help me fix this?

+6
source share
1 answer

It is undefined because what you have in data.maps[x] is not an object, but a string. Since the string does not have a property called id , you get undefined . I would probably do something like this (if I could not modify the perl script):

 var mapData = JSON.parse(data.maps[x]); //do stuff with mapData.id 

But the best thing to do is to make sure that it does not encode it as a string, but as the correct JSON.

This part in your perl script:

 my $map = qq{{"id":"$id","name":"$name","date_created":"$date"}}; 

Just pops a row from all this data. Instead, what you want is the actual perl hash, which can be translated into a JSON map / associative array. So try the following:

 my $map = { "id" => "$id", "name" => "$name", "date_created" => "$date" }; push $maps, $map; 

That way, you really have a perl hash (not just a string) that will be translated into the correct JSON.

As an example, I wrote several test codes:

 use strict; use JSON::XS; my $maps = []; push $maps, { id => 1, blah => 2 }; push $maps, { id => 3, blah => 2 }; my $j = JSON::XS->new->utf8->pretty(1); my $output = $j->encode({ success => "list of blah", maps => $maps }); print $output; 

When you run this, you will get:

 { "success" : "list of blah", "maps" : [ { "blah" : 2, "id" : 1 }, { "blah" : 2, "id" : 3 } ] } 
+10
source

Source: https://habr.com/ru/post/943462/


All Articles