我希望在Linux/Bash平台上使用命令以下面的JSON数组格式输出。任何人都可以帮忙
吗?文本文件中的data
test:test
test1:test1
test4:test4
期望输出:
{array :
[
{test:test},
{test1:test1},
{test4:test4}
]
}
使用
jq
命令行JSON PARSER:
<file jq -Rs '{array:split("\n")|map(split(":")|{(.[0]):.[1]}?)}'
{
"array": [
{
"test": "test"
},
{
"test1": "test1"
},
{
"test4": "test4"
}
]
}
选项
Rs
令jq
读为一个字符串。
脚本将此字符串分为零件以具有预期的格式。
修理您想要实际的JSON输出:split
json-parser
$ jq -nR '{array: (reduce inputs as $line ([]; . + [$line | split(":") | {(.[0]):.[1]}]))}' input.txt
{
"array": [
{
"test": "test"
},
{
"test1": "test1"
},
{
"test4": "test4"
}
]
}
$ xidel -s "input.txt" -e '
{
"array":x:lines($raw) ! {
substring-before(.,":"):substring-after(.,":")
}
}
'
x:lines($raw)
的速记,将每条新行是另一个项目的序列变成一个序列)
XQuery:
tokenize($raw,'\r\n?|\n')
也请参见This XidelcgiDemo.
。