简体   繁体   中英

Extracting key from a json

Given this JSON snippet, I'm trying to figure out to extract the name of the key corresponding to a specific "instance-id" using jq.

I'm trying this:

jq '.machines | keys as $x | if .[]."instance-id"=="wdc7ae" then <some-code-to-get-the-key>  else empty end'

where $x has all machine numbers. and "wdc7ae" is the specific "instance-id" value

 { "model": { "name": "maas2", "controller": "ctr-xenial", "cloud": "maas", "version": "2.0.1" }, "machines": { "1": { "dns-name": "10.4.0.181", "instance-id": "wdc7ae", "series": "xenial" }, "2": { "dns-name": "10.4.0.182", "instance-id": "7mx74d", "series": "xenial" }, "3": { "dns-name": "10.4.0.183", "instance-id": "rgn3ca", "series": "xenial" }, "4": { "dns-name": "10.4.0.184", "instance-id": "kmy4bh", "series": "xenial" }, "5": { "dns-name": "10.4.0.185", "instance-id": "eb38c7", "series": "xenial" } } } 

Any help is much appreciated.

Thanks 'Goldfish' from #jq irc channel. Here's the command that 'Goldfish' shared and working like a charm for me:

.machines | to_entries[] | select(.value."instance-id" == "wdc7ae").key

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM