输入数据:/tmp/h1.tabs,以制表符分隔:
INPUT A1
Flavor Controller
Comment Disabled
State DiskOne
INPUT B2
Flavor Controller
Comment Not Applicable
State Not Applicable
ConnectorCount 12
Alarm Alarm Not present
INPUT C3
Flavor Controller
Comment Not Applicable
Media Not Applicable
ConnectorCount 0
State Alarm Not present
所需的输出:
{
"A1": {
"Comment": "Disabled",
"Flavor": "Controller",
"State": "DiskOne"
},
"B2": {
"Alarm": "Alarm Not present",
"Comment": "Not Applicable",
"ConnectorCount": "12",
"Flavor": "Controller",
"State": "Not Applicable"
},
"C3": {
"Comment": "Not Applicable",
"ConnectorCount": "0",
"Flavor": "Controller",
"Media": "Not Applicable",
"State": "Alarm Not present"
}
}
每个INPUT字典键也可以是一个数组,而不是另一个字典。
{
"A1": [
{ "Comment": "Disabled" },
{ "Flavor": "Controller" },
{ "State": "DiskOne" }
],
关于我所能接近的是这样的:
jq -Rsn'[输入|。 /“ \ n” |。[] /“ \ t” | select(长度> 0)|。如$ input |(如果$ input [0] ==“ INPUT”,则$ input [1]否则{($ input [0]):$ input [1]}结尾)]'/tmp/h1.tabs>
[
"A1",
{
"Flavor": "Controller"
},
{
"Comment": "Disabled"
},
{
"State": "DiskOne"
},
"B2",
{
"Flavor": "Controller"
},
我尝试过类似$ input [0] ==“ INPUT”然后$ block = $ input [1]这样的表达式,但是我的赋值没有运气,所以我不能在其中使用赋值输出。实际上,我认为我需要的是一个变量,每次我传递它时,它设置为任何INPUTs值。然后,我可以根据需要格式化输出。我只是缺少一些关键魔术。我已经尝试了好一阵子了,这里还有更多行不通的地方...
# vim:ft=ansible:tabstop=8 expandtab shiftwidth=2 softtabstop=2
"unknown" as $block
|[
inputs
|. / "\n"
|
(
.[]
| select(length > 0)
|.
)
]
|(.[] / "\t")
|select(length > 0)
|. as $input
|
(
if $input[0] == "INPUT" then $block = $input[1] else empty end
|({($block): [($input[0]):($input[1])]})
) | add
仍在学习:-)
答案 0 :(得分:2)
reduce
是你的朋友。
reduce (inputs / "\t") as [$k, $v] ([];
if $k == "INPUT" then
.[0] = $v
else
.[1][.[0]] += {($k): $v}
end
) | .[1]
请注意,您需要在命令行上指定-n和-R选项才能使其正常工作
答案 1 :(得分:1)
使用GNU awk,gawkextlib和gawk-json:
$ gawk '
@load "json"
BEGIN{
FS="\t"
}
{
if($1=="INPUT")
tl=$2
else
data[tl][$1]=$2
}
END {
print json_toJSON(data)
}' file # | jq '.' # for eye-friendly formating
输出(辅助jq
):
{
"C3": {
"Comment": "Not Applicable",
"State": "Alarm Not present",
"ConnectorCount": "0",
"Flavor": "Controller",
"Media": "Not Applicable"
},
"A1": {
"Comment": "Disabled",
"State": "DiskOne",
"Flavor": "Controller"
},
"B2": {
"Comment": "Not Applicable",
"State": "Not Applicable",
"Alarm": "Alarm Not present",
"ConnectorCount": "12",
"Flavor": "Controller"
}
}