简体   繁体   中英

Convert JSON to headed TSV

Given a JSON file like this,

[
  {
    "h1": "x1",
    "h2": "x2"
  },
  {
    "h1": "y1",
    "h2": "y2"
  }
]

I extract it as a headed TSV using the following jq code. But I need to specify the header names twice. Is there a way to just specify the header names once? Thanks.

[
    "h1"
    , "h2"
], (.[] | [ 
    .h1
    , .h2
]) | @tsv

Here's a relatively robust jq script for printing the TSV with headers using the key names in the first object:

(.[0] | keys_unsorted) as $keys
| $keys,  (.[] | [.[$keys[]]])
| @tsv  

This of course assumes the -r command-line option.

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