加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

perl:如何在“root”键属性之外的其他内容上对JSON结构进行排序

发布时间:2020-12-15 21:48:45 所属栏目:大数据 来源:网络整理
导读: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,"",$fi
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输出 – 除了按哈希键排序.如果这就是你想要的,只需将规范方法传递给真正的参数即可.
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::bn";
    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对象和当前正在处理的散列引用; (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);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读