简体   繁体   中英

How to add a header to CSV export in jq?

I'm taking a 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'

Which does csv export well, but missing the headers as the top:

"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 can I add the header (in this case message,name ) at the top? (I know it's possible manually, but how to do it within jq ?)

只需在值前面的数组中添加标题文本即可。

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

Based on Anton's comments on Jeff Mercado's answer, this snippet will get the key names of the properties of the first element and output them as an array before the rows, thus using them as headers. If different rows have different properties, then it won't work well; then again, neither would the resulting CSV.

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

While I fully realize OP was looking for a purely jq answer, I found this question looking for any answer. So, let me offer one I found (and found useful) to others like me.

  1. sudo apt install moreutils - if you don't have them yet. Moreutils website .
  2. echo "Any, column, name, that, is, not, in, your, json, object" | cat - your.csv | sponge your.csv

Disadvantages: requires moreutils package, is not just jq -reliant, so some would understandably say less elegant.

Advantages: you choose your headers, not your JSON keys. Also, pure jq ways are bothered by the sorting of the keys, depending on your version .

How does it work?

  1. echo outputs your header
  2. cat - takes echo output from stdin (cause -) and conCATenates it with your csv file
  3. sponge waits until that is done and writes the result to same file, overwriting it.

But you could do it with tee without having to install any packages!

No, you could not, as Kos excellently demonstrates here . Not unless you're fine with loosing your csv at some point.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM