Markus
Markus

Reputation: 1965

How to use jq to extract variable keys and their values from JSON?

If I have a JSON file with variable key names like this:

{   
    "john": {"age": 40, "nickname": "jo"},
    "mary": {"age": 50, "nickname": "mo"}
}

How do I use jq to extract the keys with some of their values?

Example: Extract the names and their ages:

"john": 40
"mary": 50

Upvotes: 2

Views: 8258

Answers (3)

marcel.js
marcel.js

Reputation: 313

Try this:

to_entries[] | {(.key): .value.age}

Output:

{
  "john": 40
}
{
  "mary": 50
}

Upvotes: 1

peak
peak

Reputation: 116640

In the particular case you mention, the following filter could be used:

to_entries[] | "\"\(.key)\": \(.value.age)"

Using the -r command-line option (e.g. jq -rf program.jq) with your input produces:

"john": 40
"mary": 50

See also:

Recursive extraction of object values and parent key name using jq

Upvotes: 5

chepner
chepner

Reputation: 530823

Convert the object to an array of key/value pairs first; then you can iterate over that and access the key and associated value in tandem.

$ jq 'to_entries' tmp.json
[
  {
    "key": "john",
    "value": {
      "age": 40,
      "nickname": "jo"
    }
  },
  {
    "key": "mary",
    "value": {
      "age": 50,
      "nickname": "mo"
    }
  }
]
$ jq 'to_entries[] | "\(.key): \(.value.age)"' tmp.json
"john: 40"
"mary: 50"

Upvotes: 0

Related Questions