【发布时间】:2021-05-23 01:25:26
【问题描述】:
假设我在一个文本文件中有this JSON:
{"widget": {
"debug": "on",
"window": {
"title": "Sample Konfabulator Widget",
"name": "main_window",
"width": 500,
"height": 500
},
"image": {
"src": "Images/Sun.png",
"name": "sun1",
"hOffset": 250,
"vOffset": 250,
"alignment": "center"
},
"text": {
"data": "Click Here",
"size": 36,
"style": "bold",
"name": "text1",
"hOffset": 250,
"vOffset": 100,
"alignment": "center",
"onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
}
}}
使用 Perl,我已使用 JSON::XS 将文件读入名为 $json_obj 的 JSON 对象。
如何在 $json_obj 中搜索所有名为 name 的节点并返回/打印以下内容作为结果/输出:
widget->window->name: main_window
widget->image->name: sun1
widget->text->name: text1
注意事项:
- 与搜索词匹配的节点名称可以出现在树的任何级别
- 搜索词可以是纯文本或正则表达式
- 我希望能够提供我自己的分支分隔符来覆盖默认值,例如
->- 示例
/(为简单起见,我将把它放在一个perl中$variable)
- 示例
- 我希望能够在我的搜索中指定多个节点级别,因此指定
path进行匹配,例如:指定id/colour将返回包含名为id的节点的所有路径,即还有一个父节点,其子节点名为colour - 在结果值周围显示双引号是可选的
- 我希望能够搜索多种模式,例如
/(name|alignment)/for "查找所有名为name或alignment的节点
上面最后一个注释中显示搜索结果的示例:
widget->window->name: main_window
widget->image->name: sun1
widget->image->alignment: center
widget->text->name: text1
widget->text->alignment: center
由于 JSON 大多只是文本,我还不确定使用 JSON::XS 的好处,所以欢迎任何关于为什么这是更好或更坏的建议。
不言而喻,它需要递归,因此它可以搜索n任意深度的级别。
这是我目前所拥有的,但我只是其中的一部分:
#!/usr/bin/perl
use 5.14.0;
use warnings;
use strict;
use IO::File;
use JSON::XS;
my $jsonfile = '/home/usr/filename.json';
my $jsonpath = 'image/src'; # example search path
my $pathsep = '/'; # for displaying results
my $fh = IO::File->new("$jsonfile", "r");
my $jsontext = join('',$fh->getlines());
$fh->close();
my $jsonobj = JSON::XS->new->utf8->pretty;
if (defined $jsonpath) {
my $perltext = $jsonobj->decode($jsontext); # is this correct?
recurse_tree($perltext);
} else {
# print file to STDOUT
say $jsontext;
}
sub recurse_tree {
my $hash = shift @_;
foreach my $key (sort keys %{$hash}) {
if ($key eq $jsonpath) {
say "$key = %{$hash}{$key} \n"; # example output
}
if (ref $hash->{$key} eq 'HASH' ||
ref $hash->{$key} eq 'ARRAY') {
recurse_tree($hash->{$key});
}
}
}
exit;
上述脚本的预期结果是:
widget/image/src: Images/Sun.png
【问题讨论】:
标签: json perl data-structures