-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathjsonpath.pl
executable file
·71 lines (58 loc) · 2.25 KB
/
jsonpath.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#!/usr/bin/perl
use strict;
use warnings;
use JSON;
use Data::DPath 'dpath';
use Data::Dumper;
use Getopt::Long;
use constant USAGE => <<'HEREDOC';
Usage 1: $0 [options] <path-expression> <input-json-file>
Usage 2: $0 [options] <path-expression> # read JSON from STDIN
Note, the path syntax is not JSONPath, but rather the syntax
used by the Perl module Data::DPath. The input JSON file
must encode a single JSON object.
Example of a path: '/names/*/matches/*/uri'
OPTIONS:
--values output the value of each match on a separate line, without
any extra formatting. By default, the matches are printed
as a single JSON array. Note that this option is intended
for paths that match simple scalar values (i.e. strings and numbers).
Matches that are arrays or hashes will be omitted and a warning
will be shown.
--keys output the key of each match. By default, the matches are printed
as a single JSON array. Note that this option is intended
for paths that match hashes. Matches that aren't hashes will be omitted
and a warning will be shown.
HEREDOC
my $values_opt = 0;
my $keys_opt = 0;
die USAGE unless GetOptions('values' => \$values_opt, 'keys' => \$keys_opt);
die USAGE unless @ARGV >= 1;
my $path = shift @ARGV;
my $json_parser = JSON->new();
$json_parser->pretty(1);
$json_parser->allow_nonref(1);
my $json = join('', <>);
my $data = $json_parser->decode($json);
my @results = dpath($path)->match($data);
if ($values_opt) {
foreach my $result (@results) {
if (ref($result)) {
warn sprintf("Omitting match to hash/array, because of --values option. Match was: %s\n",
$json_parser->encode($result));
next;
}
print "$result\n";
}
} elsif ($keys_opt) {
foreach my $result (@results) {
if (ref($result) ne 'HASH') {
warn sprintf("Omitting non-hash match, because of --keys option. Match was: %s\n",
$json_parser->encode($result));
next;
}
print join("\n", keys %$result) . "\n";
}
} else {
print $json_parser->encode(\@results);
}