From 97c5c563e649eafbc72cad49273b7e32a42980c6 Mon Sep 17 00:00:00 2001 From: Mike Farah Date: Fri, 29 Jul 2022 14:33:26 +1000 Subject: [PATCH] Added CSV example for array of objects --- usage/csv-tsv.md | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/usage/csv-tsv.md b/usage/csv-tsv.md index 104624ac..e9623bcb 100644 --- a/usage/csv-tsv.md +++ b/usage/csv-tsv.md @@ -45,3 +45,32 @@ will output: i like csv because excel is cool ``` + +### Converting an array of objects to CSV + +If you have a yaml document like: + +```yaml +foo: bar +items: + - name: Tom + species: cat + color: blue + - name: Jim + species: dog + color: brown +``` + +To convert to CSV, you need to transform this into a array of CSV rows. Assuming you also want a header, then you can do: + +```bash +yq '[["name", "species", "color"]] + [.items[] | [.name, .species, .color]]' data.yaml -o=csv +``` + +to yield: + +```csv +name,species,color +Tom,cat,blue +Jim,dog,brown +```