简而言之,除了一行代码可能需要特殊处理外,是可以的。
jq通常非常适合文本处理,特别是支持正则表达式的版本。例如,有了正则表达式的支持,所给定问题陈述中所需的修剪操作就是微不足道的。
由于jq 1.5rc1包括正则表达式支持并可用自2015年1月1日起,因此以下程序假定使用jq 1.5版本;如果您希望它与jq 1.4版本一起工作,则请参阅两个“对于jq 1.4”的注释。
还请注意,该程序不能处理CSV的所有普遍性和复杂性。(有关更一般地处理CSV的类似方法,请参见https://github.com/stedolan/jq/wiki/Cookbook#convert-a-csv-file-with-headers-to-json)
# objectify/1 takes an array of string values as inputs, converts
# numeric values to numbers, and packages the results into an object
# with keys specified by the "headers" array
def objectify(headers):
# For jq 1.4, replace the following line by: def tonumberq: .;
def tonumberq: tonumber? // .;
. as $in
| reduce range(0; headers|length) as $i ({}; .[headers[$i]] = ($in[$i] | tonumberq) );
def csv2table:
# For jq 1.4, replace the following line by: def trim: .;
def trim: sub("^ +";"") | sub(" +$";"");
split("\n") | map( split(",") | map(trim) );
def csv2json:
csv2table
| .[0] as $headers
| reduce (.[1:][] | select(length > 0) ) as $row
( []; . + [ $row|objectify($headers) ]);
csv2json
示例(假设csv.csv是给定的CSV文本文件):
$ jq -R -s -f csv2json.jq csv.csv
[
{
"name": "john",
"age": 20,
"gender": "male"
},
{
"name": "jane",
"age": 30,
"gender": "female"
},
{
"name": "bob",
"age": 25,
"gender": "male"
}
]
jq
是一种以json作为输入并生成输出的工具。csv不是json。你不能期望这个工具处理它,因为它不是为此而设计的。你需要使用能够处理csv的工具或其他脚本语言。 - Jeff Mercadojq
,这可以通过一个几乎微不足道的 shell/sed 脚本来完成,例如基于 https://dev59.com/EW855IYBdhLWcg3wiU71。 - Hans Z.