Skip to content

Instantly share code, notes, and snippets.

@jeffjohnson9046
Created February 13, 2020 19:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeffjohnson9046/a542b31f03f98747d6ce4d6212091e08 to your computer and use it in GitHub Desktop.
Save jeffjohnson9046/a542b31f03f98747d6ce4d6212091e08 to your computer and use it in GitHub Desktop.
A fancy jq filter to turn JSON output into a CSV format
# From the second answer here - this SO answer gets all the credit:
# https://stackoverflow.com/questions/32960857/how-to-convert-arbitrary-simple-json-to-csv-using-jq
# This is the filter to convert JSON to CSV output:
# NOTE: This filter only works on "flat" JSON; nested properties don't work with this filter as-is.
jq -r '(.[0] | keys_unsorted) as $keys | ([$keys] + map([.[ $keys[] ]])) [] | @csv'
# For example:
aws ec2 describe-instances \
--region us-west-2 \
--query 'Reservations[].Instances[].{ commonName: Tags[?Key == `Name`]|[0].Value, instanceId: InstanceId, privateIp: PrivateIpAddress, publicIp: PublicIpAddress, zone: Placement.AvailabilityZone, status: State.Name, startedAt: LaunchTime, keyPair: KeyName }' \
--output json \
| jq -r '(.[0] | keys_unsorted) as $keys | ([$keys] + map([.[ $keys[] ]])) [] | @csv'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment