Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jq - How to print key (not value of key) and iterate over keys to print sub value

Tags:

jq

I can print the keys:

$ jq -r '.indices | keys[]'
plan
resource
user

I can print the sub value:

$ jq '.indices[] | .primaries.docs.count'
14208
1427143
104475

How do I print the key and subvalue?

plan: 14208
resource: 1427143
user: 104475
like image 444
David Vasandani Avatar asked Dec 29 '16 19:12

David Vasandani


2 Answers

Here is a solution that uses keys directly:

  .indices
| keys[] as $k
| "\($k): \(.[$k].primaries.docs.count)"
like image 199
jq170727 Avatar answered Sep 23 '22 19:09

jq170727


The following might work:

$ jq -r '.indices | to_entries[] | "\(.key): \(.value.primaries.docs.count)"' input.json
plan: 14208
resource: 1427143
user: 104475

The above assumes the input is:

{
  "indices": {
    "plan":     { "primaries": { "docs": { "count": 123 }}},
    "resource": { "primaries": { "docs": { "count": 456 }}},
    "user":     { "primaries": { "docs": { "count": 789 }}}
  }
}

to_entries will convert the object indices to an array:

[
  { "key": "plan", "value": { ... } },
  ...,
  ...
]

Which can then be easily mapped.

like image 21
Andreas Louv Avatar answered Sep 23 '22 19:09

Andreas Louv