问题
I have a below JSON and I need to convert it to a CSV. The problem I'm having is that those values have no key.
Ideally I would like CSV to look like this, I just don't know how to do it using jq.
CSV
year;points;surname;name;point1;points2;points3;city;district;url
2020;54;Smith;John;;;London;Waterloo;URL
2015;380;Helen;Smith;;;New York;Manhattan;URL
JSON
{
"draw": 0,
"total": "44",
"filtered": "8",
"data": [
[
"2020",
"54",
"Smith ",
"John",
"",
"",
"",
"London",
"Waterloo",
"URL"
],
[
"2015",
"380",
"Helen ",
"Smith",
"",
"",
"",
"New York",
"Manhattan",
"URL"
]
],
"District": []
}
回答1:
In the sample, .data[] is a stream of flat arrays, so to produce the CSV rows for the data, you could:
.data[] | @csv
回答2:
The question mentions CSV but the sample output shows semicolon-separated values, so here's a def that is like jq's built-in for tab-separated values but produces SSV, being careful to "escape" pre-existing semicolons in particular:
def ssv:
map(if type == "string" then gsub(";"; "\\;") else . end)
| @tsv
| gsub("\t"; ";") ;
For example, with the -r command-line option:
["a;b", "c\td", "e\nf"] | ssv
produces:
a\\;b;c\td;e\nf
Inverse operation
To recover the SSV values:
def ssv_to_values:
# (?<!subexp) negative look-behind
splits("(?<!\\\\);")
| gsub("\\\\\\\\;"; ";")
| gsub("\\\\n"; "\n")
| gsub("\\\\r"; "\r")
| gsub("\\\\t"; "\t")
| gsub("\\\\0"; "\u0000")
| gsub("\\\\\\\\"; "\\");
E.g. using the -r command-line option:
["a;b", "c\td", "e\nf", "g\\h"] | ssv | [ssv_to_values][]
produces:
a;b
c d
e
f
g\h
(That's a tab on the second line in the block above.)
来源:https://stackoverflow.com/questions/57205694/convert-json-array-with-values-only-to-csv-using-jq