Bash jq Basics
jq is a command-line tool that reads JSON and prints selected parts of it. It takes JSON on standard input and writes JSON or plain text out.
Read one field with .name
The filter .name reads the name field from the object. The -r option prints the string with no quotes around it.
printf '%s\n' '{"name":"Ada","city":"Lisbon","age":36}' | jq -r '.name'Walk an array with .[]
The filter .users[] walks every item of the users array. Adding .name reads the name from each item in turn.
printf '%s\n' '{"users":[{"name":"Ada"},{"name":"Bo"},{"name":"Cy"}]}' | jq -r '.users[].name'Compact output with -c and chosen fields
The construction {name: .name, city: .city} builds a new object with two chosen fields. The -c option prints that object on one line.
printf '%s\n' '{"name":"Ada","city":"Lisbon","age":36}' | jq -c '{name: .name, city: .city}'Example
printf '%s\n' '{"users":[{"name":"Ada"},{"name":"Bo"},{"name":"Cy"}]}' > users.json
echo "users:"
jq -r '.users[].name' users.json
jq -r '.users | length' users.jsonKey points
- .field: reads one named field from an object.
- -r: prints strings without quotes, for plain text output.
- .[]: walks every item of an array, one at a time.
- -c: prints each result on one compact line.
- Pipes: feed JSON to jq with a pipe, and chain filters with pipes inside the filter.
- Honest limit: jq reads JSON only, so malformed input fails instead of guessing.
In this example, the script first writes a small JSON file with three users. It prints a users label, then jq reads every name from the array. The last filter counts the array, so 3 prints after the three names.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does jq -r '.name' print for {"name":"Ada"}?