简体   繁体   中英

Using jq to get key and value from JSON

Here's a single (of many, prettified) JSON object returned by curl <url> | jq '.' curl <url> | jq '.'

{
 "63": {
    "state": {
      "on": false,
      "alert": "select",
      "mode": "automation",
      "reachable": true
    },
    "swupdate": {
      "state": "notupdatable",
      "lastinstall": "2019-09-15T11:19:15"
    },
    "type": "plug",
    "name": "Tree",
    "modelid": "XXX",
    "manufacturername": "XXX",
    "productname": "plug",
    "capabilities": {
      "certified": false,
      "control": {},
      "streaming": {
        "renderer": false,
        "proxy": false
      }
    },
    "config": {
      "archetype": "plug",
      "function": "functional",
      "direction": "omnidirectional"
    },
    "uniqueid": "00:0d:6f:ff:fe:da:c9:dc-01",
    "swversion": "2.0.022"
  }
}

I want to pipe the output to jq so that I can return the key and name from each object, eg "63" "Tree" (I am not concerned if the result is in parentheses or how the fields are separated or whether "name": is included.)

I can get keys: curl <url> | jq -r 'keys[]' curl <url> | jq -r 'keys[]'

and names: curl <url> \ jq -r '.[]{"name"}

but I can't get them both on the same line.

A succinct, efficient, and some would say elegant, solution:

map_values(.name)

One of many alternatives:

with_entries( {key, value: .value.name} )

If you want everything on a single line, you could use the -c command-line option.

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