/
sm-json
executable file
·67 lines (54 loc) · 2.1 KB
/
sm-json
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
#!/usr/bin/perl -w
BEGIN{ push @INC, $ENV{'sm_path'}."/core/internal/perl"; }
use JSON -support_by_pp; # http://search.cpan.org/~makamaka/JSON-2.53/lib/JSON.pm
sub fail { print STDERR join(" ", @_)."\n"; exit 1; }
my (
$path, $json_file, $json_file_handle, $json_object, $json, $key, $namespace,
$hash, $subhash, $reference
);
$path = shift(@ARGV);
$json_file = shift(@ARGV);
if( ! $path ) {
fail "ERROR: A json path to extract must be given as the first argument\nexample: 'system/hostname'."
} elsif ( ! $json_file ) {
fail "ERROR: A json file must be given as the second argument."
} elsif( ! -e $json_file ) {
fail "ERROR: The json file $json_file does not exist!"
}
open($json_file_handle, '<', $json_file);
$json_string = join("", <$json_file_handle>);
close($json_file_handle);
$json_object = new JSON;
$json = $json_object->allow_nonref->utf8->relaxed->escape_slash->loose->allow_singlequote->allow_barekey->decode($json_string);
@_ = split("/", $path);
$key = pop(@_);
$namespace = join("/", @_);
$hash = $json;
$subhash = {};
if($namespace) {
foreach(split("/", $namespace)) {
if(! $hash->{$_}) {
exit 0 # No value.
} elsif(exists $hash->{$_}) {
# TODO: Question: Proper way to reassign the hash to it's subhash, this
# works however I am not sure if there is an easier one liner that does
# not involve a 2nd variable (subhash).
$subhash = $hash->{$_};
$hash = $subhash; # reassign the hash to the value of the current key (namespace).
} else {
fail "ERROR: Namespace ${namespace} missing under path '".join("/", $path)."'";
}
}
}
$reference = \$hash->{$key};
if (ref($reference) eq "SCALAR") {
printf "%s\n", $hash->{$key};
} elsif (ref($$reference) eq "ARRAY") {
print STDOUT join(" ", @{$hash->{$key}}) . "\n"; # TODO: Think this out a bit more.
} elsif (ref($hash->{$key}) eq "HASH") {
# This allows for namespace querying to reflect on available keys.
printf "%s\n", join(" ",keys(%{$hash->{$key}}));
} else {
fail "ERROR: Key '$key' missing under namespace '$namespace' missing for path '$path'.";
}
exit 0; # Success!!!