简体   繁体   中英

Get parent value from json using jq

My json file looks like this;

{
 "RQBTYFE86MFC3oL": {
    "name": "Nightmode",
    "lights": [
      "1",
      "2",
      "3",
      "4",
      "5",
      "7",
      "8",
      "9",
      "10",
      "11"
    ],
    "owner": "kvovodUUfn2vlby9h9okdDhv8SrTzkBFjk6kPz2v",
    "recycle": false,
    "locked": false,
    "appdata": {
      "version": 1,
      "data": "QSXCj_r01_d99"
    },
    "picture": "",
    "lastupdated": "2018-08-08T03:21:39",
    "version": 2
  }
}

I want to get the 'RQBTYFE86MFC3oL' value by doing a query for 'Nightmode'. So far I came up with this;

jq '.[] | select(.name == "Nightmode")'

This will return me the correct part of the Json but the 'RQBTYFE86MFC3oL' part is stripped. How do I get this part as well?

A simple way to determine the key name(s) corresponding to values satisfying a certain condition is to use to_entries , as explained in the jq manual.

Using this approach, the appropriate jq filter would be:

to_entries[] | select(.value.name == "Nightmode") | .key 

with the result:

"RQBTYFE86MFC3oL"

If you want to get the key-value pair, you'd use with_entries as follows:

with_entries( select(.value.name == "Nightmode") )

If the input JSON is too large to fit comfortably in memory, then it would make sense to use jq's streaming parser (invoked with the --stream command-line option):

jq --stream '
  select(.[1] == "Nightmode" and (first|length) == 2 and first[1] == "name")
  | first | first' 

This would produce the key name.

The key idea is that the streaming parser produces arrays including pairs of the form: [ARRAYPATH, VALUE] where VALUE is the value at ARRAYPATH.

You want to get the Key Value.

So use the keys command, to return 'RQBTYFE86MFC3oL' as that is the key, the rest is the value of that key.

jq 'keys'

Here is a snippet: https://jqplay.org/s/YvpCb2PH42

Reference: https://stedolan.github.io/jq/manual/

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