Perl 处理后向 JSON 数据添加内容

vin*_*k89 2 perl json

我有一个 json 文件,我正在使用 perlJSON模块处理它。

一旦我处理它,我想在其中插入一些内容。

这是我的输入 json 文件:

{
  "sequence" : [ 
  {
    "type" : "event",
    "attribute" : {     
      "contentText" : "Test Content",
      "contentNumber" : "11"
    }
  } 
  ],
  "current" : 0,
  "next" : 1
}
Run Code Online (Sandbox Code Playgroud)

下面是我的脚本:

#!/usr/bin/perl

use strict;
use warnings;

use JSON;
use Data::Dumper;

my $needed = 2;
my $filename = "test_file.json";

my $json_text = do {
            open(my $json_fh, "<:encoding(UTF-8)", $filename)
            or die("Can't open \$filename\": $!\n");
            local $/;
            <$json_fh>
    };

my $json = JSON->new;
my $data = $json->decode($json_text);

my $aref = $data->{sequence};

print Dumper($aref);

my $number;

for my $element (@$aref) {
    $number = $element->{attribute}->{contentNumber}."\n";
}

print "Number:$number\n";

my $total = $number + $needed;

foreach my $each_number ($number+1..$total){
    print $each_number."\n";
}

print Dumper $data;
Run Code Online (Sandbox Code Playgroud)

所以我在这里需要的是contentNumber从给定的 json 文件中获取并将值增加 1 直到$needed提到并形成一个新的 json 文件。

最后它应该形成 JSON 文件,该文件应该具有如下内容:无论$needed提到什么变量值,json 应该多次形成包括初始数据在内的数据。

{
  "sequence" : [ 
  {
    "type" : "event",
    "attribute" : {     
      "contentText" : "Test Content",
      "contentNumber" : "11"
    }
  },
  {
    "type" : "event",
    "attribute" : {     
      "contentText" : "Test Content",
      "contentNumber" : "12"
    }
  },
  {
    "type" : "event",
    "attribute" : {     
      "contentText" : "Test Content",
      "contentNumber" : "13"
    }
  }
  ],
  "current" : 0,
  "next" : 1
}
Run Code Online (Sandbox Code Playgroud)

我正在考虑将数据推入foreach循环。但不知道我们如何将它放入数据对象中,它应该给我一个 json 格式的输出。

zdi*_*dim 5

从所需的输出看来,您需要sequence's 数组中的 hashref 。然后您需要将$needed其副本的数量添加到该数组中,并contentNumber在每个副本中递增。(我无法将其与显示的代码相协调,我将使用所需的输出,这似乎很清楚。)

不要忘记副本必须是副本;在这里,我使用dcloneStorable

use Storable qw(dclone);

...

my $seq_href = dclone( $data->{sequence}[0] );

for (1..$needed) { 
    ++$seq_href->{attribute}{contentNumber};
    push @{$data->{sequence}}, dclone( $seq_href );
}

my $new_json_string = $json->encode($data);  # then write it to file
Run Code Online (Sandbox Code Playgroud)

这会在我的测试中生成所需的输出 JSON。


不能仅通过赋值将包含引用的变量或数据结构复制到新的、独立的

my @copy = @ary;   # oups ... any references in there?
Run Code Online (Sandbox Code Playgroud)

问题是,当引用 中的元素@ary被复制到 中@copy的元素时@copy,作为相同的引用,指向与@ary! 中的元素相同的内存位置!因此@copy@ary绝不是独立的——它们共享数据。

有时这可能是需要的,但如果我们需要一个独立的副本,就像在这个问题中一样,那么我们需要一直遵循这些引用并实际复制数据,以便复制的结构确实有自己的数据。当然还有一些模块可以做到这一点。

根据定义,复杂(嵌套)数据结构具有对元素的引用,因此我们当然无法通过一个顶级分配获得独立的副本。

这是对潜在的偷偷摸摸和微妙错误的非常肤浅的描述。我建议阅读更多关于它的信息。出现的一个资源是Effective Perler文章