Bash jq Transform
jq transformation is building new JSON from old JSON. It picks fields, renames them, and computes new values in one filter.
Build a new object with a computed field
The construction keeps the name and adds an adult field. The adult value comes from testing the age, so it prints true here.
printf '%s\n' '{"name":"Ada","age":36}' | jq -S '{name: .name, adult: (.age >= 18)}'Join names into one string
The map step collects every name into an array. The join step then glues that array into one string with a comma and a space.
printf '%s\n' '[{"name":"Ada"},{"name":"Bo"}]' | jq -r 'map(.name) | join(", ")'Total numbers with add
The first step collects every price into an array. The add step then sums that array into one total.
printf '%s\n' '[{"name":"Ada","price":10},{"name":"Bo","price":25}]' | jq -r '[.[].price] | add'Example
printf '%s\n' '[{"item":"pen","price":10},{"item":"book","price":25},{"item":"mug","price":7}]' > orders.json
jq -S '{count: length, total: (map(.price) | add), items: (map(.item) | join(", "))}' orders.jsonKey points
- Object construction: {name: .name} builds a new object with chosen fields.
- Computed fields: (.age >= 18) inside a construction makes a true or false value.
- map: reshapes every item of an array into the same new shape.
- join: joins an array of strings into one string with a separator.
- add: adds an array of numbers into one total.
- -S: sorts object keys, so output order stays fixed.
In this example, the script first writes an orders file with three items. The count field uses length on the whole array. The total field maps prices and adds them, and the items field maps names and joins them. The -S option sorts the keys, so count, items, and total print in that fixed order.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does map(.price) | add compute from a list of orders?