【问题标题】:how to specify the order of attributes of json object in perl?如何在perl中指定json对象的属性顺序?
【发布时间】:2015-05-12 20:25:42
【问题描述】:

我正在解析 html 文件中的表格以使其成为 json 文件。 我设置了属性名称列表。每次找到指定元素时,我将其存储在 perl 哈希中,并在列表中使用下一个属性名称(请参见下面的代码)。然后我们使用 JSON 模块对哈希进行编码。但是对象中每个属性的顺序并不是它们被插入的顺序。

    sub scan_line
    {
        my($elem) = @_;   # HTML::Element
        my %result = ();
        my @tds = $elem->find("td");
        my $index = 0;    # of attrnames
        foreach my $td (@tds){
            $result{$attrnames[$index]} = $td->as_text();
            $index++;
        }
        my $text = $json->encode(\%result); 
        print TARGET $text;
    }

perl中是否有方法可以指定属性顺序或手动添加属性,如“$jobj->add_attr($attr, $value)”?

【问题讨论】:

    标签: json perl


    【解决方案1】:

    你可以使用:

    my $text = $json->sort_by(sub { $JSON::PP::a cmp $JSON::PP::b })->encode(\%result);
    

    当然,您可以使用 代替 cmp 或任何其他排序功能。请注意,如果您的 JSON 版本低于 2.0,则必须将 $json 显式创建为 JSON::PP->new(不是 JSON->new)。

    另外请注意,这会降低性能(不仅是编码调用,还有所有 $json 使用情况,AFAIU)。

    【讨论】:

      猜你喜欢
      • 2015-02-19
      • 2013-09-02
      • 2018-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-26
      • 1970-01-01
      相关资源
      最近更新 更多