I'm trying to output data in a JSON file I have with a few thousand rows to CSV. The JSON components follow this general pattern:
{
"name": "pickles",
"aliases": [
"birds"
]
}
{
"name": "cheese",
"aliases": [
"cheese1",
"cheese2"
]
}
Some of the aliases have more than 1 value (up to four) and some just have one. I'm looking for a CSV output to have two columns - one for name, and one for aliases, where the value in name will be in the name column and value for aliases will be in the aliases column (see below).
name,aliases
pickles,birds
cheese, cheese1
cheese, cheese2
I'm trying to figure out which jq command(s) to use to get this output, but I'm stuck with the error Cannot index string with string "name"
I've tried a few jq commands and I'm getting similar errors. Most recently I tried:
jq -r '.[] | . as {$name} | [$name, .name, .aliases] | @csv' filename.json
You could use --slurp
to read in the stream as an array:
$ jq -s -r '("name,aliases"), (.[] | "\(.name),\(.aliases[])")' filename.json
name,aliases
pickles,birds
cheese,cheese1
cheese,cheese2