1

I am a Perl newbie and want to loop over JSON data.
This is my code:

use JSON::XS;
my $jsonxx = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
my $text = decode_json($jsonxx);
foreach my $key(keys %$text) {
    print "$key\n";
}

and output is:

e
c
a
b
d

But I want output in the order of key-value pair given.

Expected Output:

a
b
c
d
e

Can anyone please help?

serenesat
  • 4,611
  • 10
  • 37
  • 53
Soorajlal K G
  • 778
  • 9
  • 20
  • 3
    This is not possible. JSON objects/Perl hashes are unordered by definition. You can sort the keys, though, which might still get you what you want. If you need an ordered collection, an array is what you want. – Matt Jacob Oct 20 '15 at 05:36
  • 1
    for(sort { $h->{$a} <=> $h->{$b} } keys %$h) { print "$_\n" } if you need sorted output. Sorted hash isn't possible – red0ct Oct 20 '15 at 11:55

1 Answers1

1

I guess using sort will give you expected output:

foreach my $key(sort keys %$text) {
    print "$key\n";
}
serenesat
  • 4,611
  • 10
  • 37
  • 53