将perl关联数组转换为JSON并在PHP中读取它

时间:2014-09-18 10:53:03

标签: php perl

我正在尝试在PHP脚本中读取perl关联数组。首先,我试图使用JSON模块将perl哈希转换为JSON。

下面是我用来将关联数组转换为JSON的perl脚本。文件toc.pl具有关联数组“asc_array”。

use JSON;
$j = new JSON;

require'toc.pl';

print encode_json \%asc_array; 

asc_array看起来像

%asc_array  = (
    "1"            => 'Introduction',
    "1.1"          => 'Scope',
    "1.2"          => 'Purpose',
    "2"            => 'Terminology',
    "2.1"          => 'Definitions',
    "2.2"          => 'Service Primitives',
    "2.3"          => 'Abbreviations',
    "2.4"          => 'Acronyms',
);

这里我面临一个问题,那就是在将其转换为JSON后,关联数组元素的顺序会发生变化。

所以我的问题是,即使将元素转换为JSON,我如何保持元素的顺序?

并且,在将其转换为JSON后,我正在阅读PHP脚本中的JSON。

有没有更好的方法在PHP脚本中读取perl关联数组?

2 个答案:

答案 0 :(得分:2)

使用JSON->canonical对键进行排序

use JSON;

my %asc_array = (
    "1"   => 'Introduction',
    "1.1" => 'Scope',
    "1.2" => 'Purpose',
    "2"   => 'Terminology',
    "2.1" => 'Definitions',
    "2.2" => 'Service Primitives',
    "2.3" => 'Abbreviations',
    "2.4" => 'Acronyms',
);

print JSON->new->canonical(1)->encode( \%asc_array ), "\n";

输出:

{"1":"Introduction","1.1":"Scope","1.2":"Purpose","2":"Terminology","2.1":"Definitions","2.2":"Service Primitives","2.3":"Abbreviations","2.4":"Acronyms"}

答案 1 :(得分:1)

由于您的哈希键很容易排序,为什么不在PHP脚本收到数据后对其进行排序?

use JSON::PP;
my %asc_array  = ( 
    "1"    => 'Introduction',
    "1.1"  => 'Scope',
    "1.2"  => 'Purpose',
    "2"    => 'Terminology',
    "2.1"  => 'Definitions',
    "2.2"  => 'Service Primitives',
    "2.3"  => 'Abbreviations',
    "2.4"  => 'Acronyms',
);

my $json = JSON::PP->new;
print $json->encode(\%asc_array);

然后,在PHP脚本中:

# replace this with whatever method you're using to get your JSON
# I've jumbled up the order to demonstrate the power of sorting.
$json = '{"2.3":"Abbreviations", "2.1":"Definitions", "1":"Introduction", "2.4":"Acronyms", "1.1":"Scope", "2":"Terminology", "2.2":"Service Primitives", "1.2":"Purpose"}';

$decoded = json_decode( $json, true );
ksort($decoded);

print_r($decoded);

输出:

Array
(
    [1] => Introduction
    [1.1] => Scope
    [1.2] => Purpose
    [2] => Terminology
    [2.1] => Definitions
    [2.2] => Service Primitives
    [2.3] => Abbreviations
    [2.4] => Acronyms
)