【问题标题】:Perl Json parser , changing the order of elements in the jsonPerl的JSON分析器,改变元素的顺序在JSON
【发布时间】:2016-12-13 20:17:14
【问题描述】:

我正在使用 perl 的 json 模块来解析一个 json 对象并更新它。

更新我们看到的json对象后,json里面元素的顺序发生了变化,我理解json中元素的顺序无关紧要。

但是我想知道有没有办法可以保持与输入 json 对象相同的顺序?因为我们与许多客户端共享更新 json,我担心如果有人使用解析器,其中元素的顺序是硬编码的.

【问题讨论】:

  • 你能分享一些你用来读取和修改 JSON 对象的代码

标签: json perl


【解决方案1】:

您需要使用某种绑定哈希来强制键的顺序:Tie::IxHash。

以下是概念证明:

#!/usr/bin/env perl

use strict;
use warnings;
use v5.10;

use JSON::XS;

my $JSON = JSON::XS->new->utf8->indent->space_after->convert_blessed;

my $data = {
    a => 1,
    b => 2,
    c => 3,
    d => 4,
    e => 5,
};

say $JSON->encode($data);      # Keys are unordered

bless $data, 'MyAlphaHash';

say $JSON->encode($data);      # Keys are alphabetized

package MyAlphaHash;

use Tie::IxHash;

sub TO_JSON {
    my $self = shift;

    tie my %hash, 'Tie::IxHash', %$self;

    tied(%hash)->Reorder( sort keys %hash );

    return \%hash;
}

输出:

$ perl ordered.pl
{
   "e": 5,
   "c": 3,
   "a": 1,
   "b": 2,
   "d": 4
}

{
   "a": 1,
   "b": 2,
   "c": 3,
   "d": 4,
   "e": 5
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-06
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 2022-08-18
    相关资源
    最近更新 更多