perl:如何在"root"键属性之外的东西上对JSON结构进行排序

knb*_*knb 8 sorting perl json

Perl:如何使用JSON :: PP对复杂结构进行排序?

从JSON文档:

由于排序例程在JSON :: PP范围内运行,给定的子例程名称和特殊变量$ a,$ b将以'JSON :: PP ::'开头.

这是我的尝试,似乎没有用

open my $fh, ">", $file or warn " exportAsJSON: can't open file: '$file': $!";
print $fh  $coder->sort_by(sub {$_->{column_def}->{$JSON::PP::a} cmp $_->{column_def}->{$JSON::PP::b}  } )->encode(\%json);
close $fh;
Run Code Online (Sandbox Code Playgroud)

我想按键排序,然后在"column_def"下面的属性键上的column_def属性,即density,depth_in_m,mag_sus:

{
    "column_def":
        {
            "depth_in_m":
                {
                    "names":"depth_in_m",
                    "pos":"0"
                },
            "mag_sus":
                {
                    "names":
                        {
                            "A_ALIAS":"Mag-Sus.",
                            "A_DESC":"magnetic susceptibility in SI",
                            "ATTRIBUTE":"MAG_SUS"
                        },
                    "pos":"2"
                },
            "density":
                {
                    "names":
                        {
                            "A_ALIAS":"Density",
                            "A_DESC":"density in gm\/cc",
                            "ATTRIBUTE":"DENSITY"
                        },
                    "pos":"1"
                }
        },
    "data":
        {
            "depth_in_m":"14.635",
            "mag_sus":"n.a.",
            "density":"n.a."
        }
}
Run Code Online (Sandbox Code Playgroud)

FMc*_*FMc 14

我不确定我是否理解你希望如何排序JSON输出 - 除了按哈希键排序.如果这就是你想要的,只需传递canonical一个真正的参数.

use strict;
use warnings;

use JSON::PP;

# A simple hash-of-hashes for exploration.
my $h = {
    Z => { c => 1, d => 2 },
    A => { a => 3, r => 4 },
    B => { c => 5, x => 6 },
    S => { q => 7, d => 8 },
};

my $js = JSON::PP->new;
$js->canonical(1);

my $output = $js->encode($h);
print $output;
Run Code Online (Sandbox Code Playgroud)

如果您确实使用了该sort_by方法,则$_sort块内使用是没有意义的:它代表什么?从文档中不清楚sort_by代码将接收哪些参数.使用Data::Dumper这样:

use Data::Dumper qw(Dumper);

my $sorter = sub {
    # See what's going on.
    print "$JSON::PP::a cmp $JSON::PP::b\n";
    print Dumper(\@_, $_);
    <STDIN>;

    # Sort hash keys alphabetically.
    $JSON::PP::a cmp $JSON::PP::b;
};

my $output = $js->sort_by($sorter)->encode($h);
Run Code Online (Sandbox Code Playgroud)

你可以推断出这样的sort_by工作:(1)它接收两个参数,JSON::PP对象和当前正在使用的散列引用; (2)$JSON::PP::a$JSON::PP::b变量保持被比较的散列键.但请注意,散列引用是指JSON输出,因为它是从叶节点向上构建的.它不涉及您的原始数据结构.这似乎使编写比较器的任务有点棘手.祝好运.

my $sorter = sub {
    my ($json_pp_object, $hash_ref) = @_;

    # Write your own comparator here.
};

my $output = $js->sort_by($sorter)->encode($h);
Run Code Online (Sandbox Code Playgroud)