Reputation: 1399
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:
name age pets
Tim 15 cats,dogs
Joe 11 rabbits,birds
...
ideal 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"-
}, ...
]
Upvotes: 7
Views: 5460
Reputation: 116870
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, e.g. like this:
jq -R -f program.jq input.tsv
If you want the result as an array, simply enclose the entire filter above in square brackets.
Upvotes: 4
Reputation: 158100
Like this:
jq -rRs 'split("\n")[1:-1] |
map([split("\t")[]|split(",")] | {
"name":.[0],
"age":.[1],
"pet":.[2]
}
)' input.tsv
Upvotes: 7