How to get parent node from JSON?

37 Views Asked by At

[Update my question little bit]

I have below JSON in a test.json file. And I'm trying to figure out how to get all the root names, who's values are completely dynamic in nature.

{
       "result_set": {
        "/api/device/4756": {
            "name": "Arbitrator",
            "ip": "127.0.0.1",
            "hostname": "acme.arbitrate.com"
        },
        "/api/device/4757": {
            "name": "Auditor",
            "ip": "127.0.0.2",
            "hostname": "acme.auditor.com"
        },
        "/api/device/4758": {
            "name": "Augumentor",
            "ip": "127.0.0.3",
            "hostname": "acme.augumentor.com"
        }
    }
}

So far I've tried but it doesn't return what I'm looking for....

cat test.json | jq -r '["names"], (.result_set | [])'

I'm looking for a result that looks like below ...

/api/device/4756, Arbitrator, 127.0.0.1, acme.arbitrate.com
/api/device/4757, Auditor, 127.0.0.2, acme.auditor.com
/api/device/4758, Augumentor, 127.0.0.3, acme.augumentor.com
1

There are 1 best solutions below

0
pmf On

Just fetch the keys using keys_unsorted:

.result_set | keys_unsorted[]

Demo


Would it be possible to further enhance this to give below output?

/api/device/4756, Arbitrator, 127.0.0.1, acme.arbitrate.com 
/api/device/4757, Auditor, 127.0.0.2, acme.auditor.com
/api/device/4758, Augumentor, 127.0.0.3, acme.augumentor.com

Then store the key to access it later:

.result_set | keys_unsorted[] as $key | .[$key] | [$key, .name, .ip, .hostname]
| join(", ") # or @csv

Demo

Or use to_entries instead, which breaks up an object into a list of key-value pairs:

.result_set | to_entries[] | [.key, .value.name, .value.ip, .value.hostname]
| join(", ") # or @csv

Demo