簡體   English   中英

Perl將JSON響應解析為數組

[英]Perl parse JSON response as an array

我有一個包含大量派生列的長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僅適用於數組,因此我如何將服務器的響應解析為數組?

在后端,您可以將數據放入單獨的數組中,而不是將每一行添加到哈希中:

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

或者在前端,將關聯數組轉換為常規數組:

$http.get("/folder/ofSubroutine.cgi")
    .then(function(minutes_results) {
        console.log(minutes_results);
        var minutes_results_as_array = [];
        for (var key in minutes_results) {
            if (key != "error") {
                minutes_results[key].id = key;
                minutes_results_as_array.push(minutes_results[key]);
            }
        }
        // display minutes_results_as_array as you see fit
      } );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM