7

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?

1
  • There is no array in the data. – Kusalananda Nov 12 '18 at 16:51
10
$ 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:

3
  • Would this still work if some of the keys do not contain the corresponding attribute (in this case .conns) or would it generate an error? – gented Oct 5 '20 at 9:26
  • What happens when you try it? – glenn jackman Oct 5 '20 at 11:48
  • I do get an error (in particular "Cannot index number with string <stringname>": therefore my comment can be rephrased to how to specify the correct grammar to avoid it :) – gented Oct 5 '20 at 12:03
0

alternative solution (jtc) facilitates the ask with a bit of standard cli:

bash $ echo $OUTPUT | jtc -rl -w'[+0]' -w'[+0][conns]' | sed 's/: {.*//g; s/^"conns"://' | xargs -n2
1 1.0
2 2.0
bash $ 

jtc (unlike jq) is a utility which confines its functionality to json operations only (so its interface is drastically simpler), however manipulating articles outside of JSON data model is offloaded to external unix tools

EDIT: Newer version of jtc supports a simpler solution:

bash $ jtc -w'<conns>l:<con>v[-1]<key>k' -T '"{key} {con}"' -qq <<<$OUTPUT
1 1.0
2 2.0
bash $ 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.