我的文本文件中的数据格式为:
alex street1 253465873 [email protected]
john street2 442893646 [email protected]
kevin street3 125234763 [email protected]
我需要将此数据转换为带有标头的 json 格式:
"name" "street" "phone" "e-mail"
答案1
你可以阅读原始输入并将其分割为空格分隔的字段,jq
如下所示:
$ cat file.txt |
jq -nR '[inputs | split(" ") | { "name": .[0], "street": .[1], "phone": .[2], "e-mail": .[3] }]'
[
{
"name": "alex",
"street": "street1",
"phone": "253465873",
"e-mail": "[email protected]"
},
{
"name": "john",
"street": "street2",
"phone": "442893646",
"e-mail": "[email protected]"
},
{
"name": "kevin",
"street": "street3",
"phone": "125234763",
"e-mail": "[email protected]"
}
]
或者,对于简单(非嵌套)表格数据,您可以使用磨坊主
mlr --inidx --ojson --jvstack rename '1,name,2,street,3,phone,4,e-mail' file.txt
答案2
$ column --table --separator=" " --table-columns name,street,phone,email --json test.txt
{
"table": [
{
"name": "alex",
"street": "street1",
"phone": "253465873",
"email": "[email protected]"
},{
"name": "john",
"street": "street2",
"phone": "442893646",
"email": "[email protected]"
},{
"name": "kevin",
"street": "street3",
"phone": "125234763",
"email": "[email protected]"
}
]
}
答案3
使用磨坊主( mlr
) 将无标头和空格分隔的数据转换为 JSON:
$ mlr --n2j label name,street,phone,e-mail file
{ "name": "alex", "street": "street1", "phone": 253465873, "e-mail": "[email protected]" }
{ "name": "john", "street": "street2", "phone": 442893646, "e-mail": "[email protected]" }
{ "name": "kevin", "street": "street3", "phone": 125234763, "e-mail": "[email protected]" }
输出是每个输入记录的单独 JSON 对象。该选项是(“输入是隐式整数索引(nidx)”)与(“输出是 JSON”)--n2j
的简写。--inidx
--ojson
该label
子命令按顺序重命名字段。
您想将生成的对象集包装在数组中,请使用--jlistwrap
:
$ mlr --n2j --jlistwrap label name,street,phone,e-mail file
[
{ "name": "alex", "street": "street1", "phone": 253465873, "e-mail": "[email protected]" }
,{ "name": "john", "street": "street2", "phone": 442893646, "e-mail": "[email protected]" }
,{ "name": "kevin", "street": "street3", "phone": 125234763, "e-mail": "[email protected]" }
]
答案4
试试这个 awk 命令:
$ awk '{for (i=1;i<=NF;i++){$i="\""$i"\"";printf $i" "}};{printf"\n"}' infile
"alex" "street1" "253465873" "[email protected]"
"john" "street2" "442893646" "[email protected]"
"kevin" "street3" "125234763" "[email protected]"