gpt4 book ai didi

perl:如何对除 "root"键属性以外的内容排序JSON结构

转载 作者:行者123 更新时间:2023-12-04 05:59:07 24 4
gpt4 key购买 nike

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

从JSON文档中:

As the sorting routine runs in the JSON::PP scope, the given subroutine name and the special variables $a, $b will begin '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;

我想按键排序,然后按“column_def”下方的属性键上的column_def属性,即
密度,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."
}
}

最佳答案

我不确定我是否理解您希望如何对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;

如果您确实使用 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);

您可以推断 sort_by的工作方式如下:(1)它接收两个参数,即 JSON::PP对象和当前正在使用的hash ref; (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);

关于perl:如何对除 "root"键属性以外的内容排序JSON结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3532067/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com