How Do I Select Multiple Fields in Jq?

How Do I Select Multiple Fields in Jq?

My input file looks something like this:

{
  "login": "dmaxfield",
  "id": 7449977,
  ...
}
{
  "login": "dmaxfield",
  "id": 7449977,
  ...
}

I can get all the login names with this : cat members | jq '.[].login'

but I have not been able to crack the syntax to get both the login and id?

1

4 Answers

You can use jq '.[] | .login, .id' to obtain each login followed by its id.

8

This works for me:

> echo '{"a":1,"b":2,"c":3}{"a":1,"b":2,"c":3}' | jq '{a,b}'
{
  "a": 1,
  "b": 2
}
{
  "a": 1,
  "b": 2
}
3

Just provide one more example here (jq-1.6):

Walk through an array and select a field of an object element and a field of object in that object

echo '[{"id":1, "private_info": {"name": "Ivy", "age": 18}}, {"id":2, "private_info": {"name": "Tommy", "aga": 18}}]' | jq ".[] | {id: .id, name: .private_info.name}" -

{
  "id": 1,
  "name": "Ivy"
}
{
  "id": 2,
  "name": "Tommy"
}

Without the example data:

jq ".[] | {id, name: .private_info.name}" -

.[]: walk through an array

{id, name: .private_info.name}: take .id and .private_info.name and wrap it into an object with field name "id" and "name" respectively

1

In order to select values which are indented to different levels (i.e. both first and second level), you might use the following:

echo '[{"a":{"aa":1,"ab":2},"b":3,"c":4},{"a":{"aa":5,"ab":6},"b":7,"c":8}]' \
     | jq '.[]|[.a.aa,.a.ab,.b]'

[
  1,
  2,
  3
]
[
  5,
  6,
  7
]
0

Your Answer

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

James H. Sterling
Author

James H. Sterling

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.