Perl将JSON响应解析为数组

时间:2015-09-08 18:24:35

标签: json angularjs perl

我有一个很长的SQL查询,包含很多派生列,我试图让它显示在一个有角度的页面中。我达到了从数据库中获取json响应的程度,但它将每行作为一个大对象而不是数组返回。我正在使用perl来查询数据库,我已经尝试了很多方法来解析它,但我还没有得到它。

子程序:

require fileWithAllImports.pl #has CGI, JSON, etc
%response                 = {};
$response{error}{code}    = "0";
$response{error}{message} = "OK";

$sql = "select c.title as Content....";
$sql  = &database_escape_sql($sql); #I think its self-explanatory what this does
%hash = &database_select_as_hash_with_auto_key(
$sql,"content ... "); #more columns

foreach $i ( keys %hash ) {

        $id                              = $i;
        $response{$i}{content}           = $hash{$i}{content};
       ...
    } #again all of the columns

print_json_response(%response);

角度呼叫:

$http.get("/folder/ofSubroutine.cgi")
        .then(function(minutes_results) {
            console.log(minutes_results);

和json repsonse:

{"6":{"derivedcolumn":"123","anotherderived":"987",..},"11":{"derived column":"123"}...}

我相信ng-repeat仅适用于数组,那么如何将服务器的响应解析为数组呢?

1 个答案:

答案 0 :(得分:0)

在后端,您可以将数据放入单独的数组中,而不是将每一行添加到哈希:

int newPosition = pos;
Items undoObject = tm;
ArrayList<Items> oldList = mArrayList;
ArrayList<Items> newList = new ArrayList<Items>();
int i = 0;
for(Items item : oldList) {
    if(i == newPosition) {
    newList.add(undoObject);
    } else {
    newList.add(item);
    }    
}

或者在前端,将关联数组转换为常规数组:

foreach $i ( keys %hash ) {
    push @{$response{data}}, { id => $i,
                               content => $hash{$i}{content},
                               ... ,
                             };
}
print_json_response( %response );