Perl在处理后向JSON数据添加内容
我有一个json文件,我正在使用perlPerl在处理后向JSON数据添加内容,json,perl,Json,Perl,我有一个json文件,我正在使用perljson模块处理它 一旦我处理它,我想在其中插入一些内容 这是我的输入json文件: { "sequence" : [ { "type" : "event", "attribute" : { "contentText" : "Test Content", "contentNumber" : "11" } } ], "current" : 0, "next" : 1 }
json
模块处理它
一旦我处理它,我想在其中插入一些内容
这是我的输入json文件:
{
"sequence" : [
{
"type" : "event",
"attribute" : {
"contentText" : "Test Content",
"contentNumber" : "11"
}
}
],
"current" : 0,
"next" : 1
}
下面是我的脚本:
#!/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;
我正在考虑将数据推送到
foreach
循环中。但是,我们不知道如何将其放入数据对象中,该数据对象应该给我一个json格式的输出。从所需的输出来看,您似乎需要位于序列数组中的hashref。然后您需要向该数组添加$needed
副本数,每个副本中的contentNumber
都会递增。(我无法将其与显示的代码相协调,我将使用所需的输出,这似乎很清楚。)
不要忘记副本必须是深度副本;†这里我使用了dclone
from
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
这将在我的测试中生成所需的JSON输出
†包含引用的变量或数据结构不能仅通过赋值复制到新的独立变量或数据结构中
my @copy = @ary; # oups ... any references in there?
问题是当@ary
中的引用元素被复制到@copy
中时,@copy
中的那些元素作为相同的引用,指向与@ary
中的元素相同的内存位置!因此,@copy
和@ary
绝不是独立的——它们共享数据
有时这可能是需要的,但是如果我们需要一个独立的副本(就像在这个问题中),那么我们需要一直遵循这些引用并实际复制数据,以便复制的结构确实有它自己的数据。当然,还有一些模块可以做到这一点
根据定义,复杂(嵌套)数据结构具有元素引用,因此我们肯定无法通过一个顶级赋值获得独立副本
这是一个非常肤浅的描述一个潜在的狡猾和微妙的错误。我建议多读一读。出现的一个资源是。是的,我可以在我的代码中看到转储程序($data)
中的数据。那么,我如何将其放入.json
文件中呢?我可以直接将其转储到json文件中吗?有什么建议吗?@vinodk89啊,对,那(在问题中没有注意到)--使用相同的模块将其转换回JSON,然后将其作为文件写出来。我将添加这个…@vinodk89添加了一行代码,从修改后的$data
(这就是你的意思吗?)生成一个新的JSON字符串,并对需要“deep”copy.Yep@zdim进行了大量评论。我已经对$data
中的数据进行了编码并写入了一个文件。这个有用!!非常感谢。
my @copy = @ary; # oups ... any references in there?