How to add header to CSV export in jq?

I take the modified command from the jq tutorial :

 curl 'https://api.github.com/repos/stedolan/jq/commits?per_page=5' \ | jq -r -c '.[] | {message: .commit.message, name: .commit.committer.name} | [.[]] | @csv' 

What makes csv good to export but no headers:

 "Fix README","Nicolas Williams" "README: send questions to SO and Freenode","Nicolas Williams" "usage() should check fprintf() result (fix #771)","Nicolas Williams" "Use jv_mem_alloc() in compile.c (fix #771)","Nicolas Williams" "Fix header guards (fix #770)","Nicolas Williams" 

How to add a title (in this case message,name ) at the top? (I know this is possible manually, but how to do it in jq ?)

+8
json csv jq
source share
3 answers

Based on Antonโ€™s answers to Jeff Mercadoโ€™s answer, this snippet will receive the key property names of the first element and display them as an array before the lines, thus using them as headers. If different lines have different properties, then this will not work; then again, none of the CSVs received.

map({message: .commit.message, name: .commit.committer.name}) | (.[0] | to_entries | map(.key)), (.[] | [.[]]) | @csv

+6
source share

Just add the header text to the array before the values.

 ["Commit Message","Committer Name"], (.[].commit | [.message,.committer.name]) | @csv 
+7
source share

While I was fully aware that the OP was looking for a purely jq answer, I found this question looking for any answer. So let me suggest the one that I found (and found useful) for others like me.

  • sudo apt install moreutils - if you do not already have them. Moreutils website .
  • echo "Any, column, name, that, is, not, in, your, json, object" | cat - your.csv | sponge your.csv

Disadvantages: moreutils package is moreutils , it is not just jq -reliant, so some of them, for obvious reasons, will be less elegant.

Advantages: you choose headers, not your JSON keys. Also, jq clean paths jq concerned about sorting keys depending on your version .

How it works?

  • echo prints your title
  • cat - takes an echo exit from stdin (reason -) and conCATenate it with your csv file
  • sponge waits until it is done, and writes the result to the same file, overwriting it.

But you can do it with tee without installing any packages!

No, you could not, because Kos is excellently demonstrating here . Not if you fail to lose your csv at some point.

0
source share

All Articles