我正在尝试创建一个
JSON对象,列出与特定用户关联的映射,但从未使用过嵌套的JSON对象.这就是我要的:
{ "success":"list of users maps","maps":[ { "id":"1","name":"Home to LE","date_created":"1366559121" },{ "id":"2","name":"Test 1","date_created":"1366735066" } ] }
使用这个perl代码:
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 });
但我得到的输出是:
{ "success":"list of users maps","maps":[ "{\"id\":\"1\",\"name\":\"Home to LE\",\"date_created\":\"1366559121\"}","{\"id\":\"2\",\"name\":\"Test 1\",\"date_created\":\"1366735066\"}" ] }
因此,当我在Javascript中处理它时,data.maps [x] .id是未定义的.我很确定输出的JSON格式不正确.
任何人都可以帮我修复它吗?
解决方法
它是未定义的,因为您在data.maps [x]中的内容不是对象,而是字符串.由于字符串没有名为id的属性,因此未定义.我可能会做这样的事情(如果我无法更改perl脚本):
var mapData = JSON.parse(data.maps[x]); //do stuff with mapData.id
但更好的做法是确保它不会将其编码为字符串,而是将其编码为正确的JSON.
这部分在你的perl脚本中:
my $map = qq{{"id":"$id","date_created":"$date"}};
只是从所有数据中生成带引号的字符串.相反,你想要的是一个实际的perl哈希,可以转换成JSON map / associative-array.试试这个:
my $map = { "id" => "$id","name" => "$name","date_created" => "$date" }; push $maps,$map;
这样你实际上有一个perl哈希(而不仅仅是一个字符串)将被转换为适当的JSON.
作为一个例子,我写了一些测试代码:
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;
当你运行它时,你得到:
{ "success" : "list of blah","maps" : [ { "blah" : 2,"id" : 1 },{ "blah" : 2,"id" : 3 } ] }