in reply to search json for key with particular value
Here is some code that does the recursion and returns all objects that include a "componentId". I marked the line where you would edit the logic to only return objects that have componentId whose value matches.
#!perl use 5.012; # strict, // use warnings; use JSON; # create the JSON object from a string (you could get it from a file, +or whatever) my $json = JSON->new->allow_nonref(); my $string = <<EOT; { "infra": { "config": { "rack": [ { "componentId": "xxx-001", "model": "xxx", "server": [ { "componentId": "server-001", "type": "xxxx", "model": "xxxx", "role": "Management", "specificAttributes": "" } ] }] }, "platform": { "config": { "mgmtser": [{ "componentId": "sr-001", "domainName": "xxxxx", "thinDiskMode": true, "deployment": "small" } ]} } } } EOT my $href = $json->decode($string); #recurse through the top level my @retvals = h_recurse($href); use Data::Dumper; print Dumper @retvals; exit; # define two subroutines, for recursing a hashref or an arrayref sub h_recurse { my $r = shift; my @ret = (); die "'$r' not a hashref" unless UNIVERSAL::isa($r,'HASH'); # go through each pair while(my ($key,$val) = each %$r ) { # if it's a hash or array ref, recurse into it; add the return +s from the recursion to your active return list push @ret, h_recurse($val) if UNIVERSAL::isa($val,'HASH'); push @ret, a_recurse($val) if UNIVERSAL::isa($val,'ARRAY'); # if a literal key/value pair matches your requirements, add i +t to your return list push @ret, $r if $key eq 'componentId'; # change the logic her +e if you want only componentId whose value matches something specific } # once done, return @ret; } sub a_recurse { my $r = shift; my @ret = (); die "'$r' not an arrayref" unless UNIVERSAL::isa($r,'ARRAY'); for my $val (@$r) { push @ret, h_recurse($val) if UNIVERSAL::isa($val,'HASH'); push @ret, a_recurse($val) if UNIVERSAL::isa($val,'ARRAY'); } return @ret; }
I am not a JSON expert, so there may be a way using the JSON module or helper module to do a more efficient recursive search than my manual answer. I yield to wiser monks.
--
edit: JSON module will be faster if you have installed JSON::XS, because it will try to use that if possible.
edit2: updated code to use the OP-style data, as interpreted by hippo, rather than my proprietary data; also fixed post and code so "componentId" had correct case on the "d"
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: search json for key with particular value
by rahulruns (Scribe) on Dec 16, 2020 at 14:55 UTC |