简体   繁体   English

使用数组将带有数组的tsv转换为JSON

[英]Converting tsv with arrays to JSON with jq

i found jq very helpful in converting tsv to JSON file, however, i want to figure out how to do it with jq when i have array in my tsv: 我发现jq在将tsv转换为JSON文件中非常有帮助,但是,当我在tsv中有数组时,我想弄清楚如何使用jq进行操作:

name    age    pets
Tim    15    cats,dogs
Joe    11    rabbits,birds
...

ideal JSON: 理想的JSON:

[
 {
  name: "Tim",
  age: "15",
  pet:["cats","dogs"]
 },
  name: "Joe",
  age: "11",
  pet:["rabbits","birds"]
 }, ...
]

This is the command i tried: 这是我尝试的命令:

cat file.tsv | jq -s  --slurp --raw-input --raw-output 'split("\n") | .[1:-1] | map(split("\t")) |
        map({"name": .[0],
             "age": .[1],
             "pet": .[2]})'

and the output the the above command is: 上面命令的输出是:

[
 {
  name: "Tim",
  age: "15",
  pet:"cats,dogs"
 },
  name: "Joe",
  age: "11",
  pet:"rabbits,birds"-
 }, ...
]

Like this: 像这样:

jq -rRs 'split("\n")[1:-1] |
         map([split("\t")[]|split(",")] | {
                 "name":.[0],
                 "age":.[1],
                 "pet":.[2]
             }
    )' input.tsv

In case the name includes any commas, I'd go with the following, which also avoids having to "slurp" the input: 如果名称中包含任何逗号,我将使用以下内容,这也避免了“输入”输入:

inputs
| split("\t")
| {name: .[0], age: .[1], pet: .[2]}
| .pet |= split(",") 

To skip the header, simply invoke jq with the -R option, eg like this: 要跳过标题,只需使用-R选项调用jq,例如:

jq -R -f program.jq input.tsv

If you want the result as an array, simply enclose the entire filter above in square brackets. 如果要将结果作为数组,只需将上面的整个过滤器括在方括号中即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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