rahulruns has asked for the wisdom of the Perl Monks concerning the following question:
In a json if I want to search for a key which could be at any level and multiple places, how do I do it. Example I have below JSON. In JSON there are places where componentID is present. Each ComponentId is different. I need to search value of that componentId in json and where it matches pick that object in json. This is kind of function which helps to pickup that object out of json based on componentId value. Any module to achieve this or any idea to help on this
json "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",
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: search json for key with particular value
by hippo (Archbishop) on Dec 15, 2020 at 15:25 UTC | |
Sounds like a job for Data::DPath:
🦛 | [reply] [d/l] |
|
Re: search json for key with particular value
by pryrt (Abbot) on Dec 15, 2020 at 14:46 UTC | |
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.
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" | [reply] [d/l] |
by rahulruns (Scribe) on Dec 16, 2020 at 14:55 UTC | |
Thank you for your answer I was thinking of recursing structure but was looking if there is any other possibility except recursing structure | [reply] |
|
[OT] Re: search json for key with particular value
by erix (Prior) on Dec 17, 2020 at 13:23 UTC | |
Not a perl answer, and probably not even useful for the OP, unless the JSON is large/many, and a database is at hand. Nevertheless, and Just For Fun: indexed JSON in PostgreSQL:
All this is in released PostgreSQL, i.e., postgres 13. But JSON indexing in postgres is still an area of intensive development - more JSON flexibility is in the dev pipeline) (TWIMC, for future tech detail (PDFs, sometimes rather low-level): http://www.sai.msu.su/~megera/postgres/talks ) | [reply] [d/l] |