2010-09-12 9 views
6

Dopo il codice perl ho scritto per analizzare un array in JSON. Ma la matrice restituita ha lunghezza 1 e non sono in grado di scorrere correttamente su di essa. Quindi il problema è che non sono in grado di usare l'array restituito.Analisi di un array codificato in JSON tramite perl

#!/usr/bin/perl 
use strict; 

my $json_text = '[ {"name" : "abc", "text" : "text1"}, {"name" : "xyz", "text" : "text2"} ]'; 

use JSON; 
use Data::Dumper::Names; 

my @decoded_json = decode_json($json_text); 
print Dumper(@decoded_json), length(@decoded_json), "\n"; 

L'uscita arriva:

$VAR1 = [ 
    { 
     'text' => 'text1', 
     'name' => 'abc' 
     }, 
     { 
     'text' => 'text2', 
     'name' => 'xyz' 
     } 
    ]; 
1 

risposta

16

I decode_json function restituisce un rifarray, non una lista. È necessario dereferenziarlo per ottenere l'elenco:

my @decoded_json = @{decode_json($json_text)}; 

si consiglia di leggere perldoc perlreftut e perldoc perlref

+0

Il dereferenziamento aiuta un po '. Ora sono in grado di scorrere l'array restituito. Ma ancora ottengo la lunghezza dell'array = 1 –

+0

Il mio male. Stavo usando la lunghezza (@decoded_json) per ottenere la lunghezza dell'array !! –

1

Per quanto riguarda JSON, si potrebbe voler assicurarsi di installare il modulo JSON :: XS come è più veloce e più stabile rispetto alla pura implementazione di perl inclusa con il modulo JSON. Il modulo JSON utilizzerà automaticamente JSON :: XS quando è disponibile.