Reputation: 1965
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
Reputation: 313
Try this:
to_entries[] | {(.key): .value.age}
Output:
{
"john": 40
}
{
"mary": 50
}
Upvotes: 1
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
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