Get values for a given key and its parent with jq

jqjson

I've got a JSON object like so:

{
  "1": {
    "available_memory": 1086419656.0,
    "available_memory_no_overbooking": 1086419656.0,
    "conns": 1.0
  },
  "2": {
    "available_memory": 108641236.0,
    "available_memory_no_overbooking": 10861216.0,
    "conns": 2.0
  }
}

I want to retrieve the value of "conns" atribute for each object id. I am new at jq and I cant found clear examples.

I have tried the following:

echo "$OUTPUT" | jq -r .[].conns

Which returns all the values for conns, but thats is not what I needed. The spected output would be:

1 1.0
2 2.0

Any ideas?

Best Answer

$ jq -r 'keys[] as $k | "\($k) \(.[$k].conns)"' file.json
1 1
2 2

Seems like jq translates 1.0 to 1 and 2.0 to 2. Altering the input for clarity:

$ cat file.json
{
  "1a": {
    "available_memory": 1086419656.0,
    "available_memory_no_overbooking": 1086419656.0,
    "conns": 1.1
  },
  "2b": {
    "available_memory": 108641236.0,
    "available_memory_no_overbooking": 10861216.0,
    "conns": 2.2
  }
}
$ jq -r 'keys[] as $k | "\($k) \(.[$k].conns)"' file.json
1a 1.1
2b 2.2

Refs:

Related Question