json 文档的条件转换
conditional transformation on json doc
我有以下 json 文档 (file.json):
[{
"mount": "/",
"size": "45G",
"usedperc": "26"
},
{
"mount": "/opt",
"size": "197G",
"usedperc": "20"
},
{
"mount": "/tmp",
"size": "5.0G",
"usedperc": "8"
}]
鉴于此文档,我想转换为具有以下结构的不同文档:
[
{
"key": "val1",
"mnt": "/-rootFS",
"key3": {
"key4": "val4"
}
},
{
"key": "val1",
"mnt": "/opt-optFS",
"key3": {
"key4": "val4"
}
},
{
"key": "val1",
"mnt": "/tmp-tmpFS",
"key3": {
"key4": "val4"
}
}
]
然而,当尝试使用 js 应用转换时,它在文档的第一次迭代时停止,并且不处理文档的其余部分:
jq ' [{
"key":"val1",
"mnt": .[]|(if select(.mount == "/") then "/-rootFS" elif select(.mount == "/opt") then "/opt-optFS" elif select(.mount == "/tmp") then "/tmp-tmpFS" else . end ) ,
"key3":{
"key4": "val4"
}}]' < file.json
#output
[
{
"key": "val1",
"mnt": "/-rootFS",
"key3": {
"key4": "val4"
}
}
]
不知道该怎么做,我尝试了很多不同的方法,主要是遇到“无法使用字符串“mount”索引数组”错误。顺便说一句,这实际上只是一个更大的 jq 表达式的测试用例,所以如果可能的话,我想用 jq 来做
这是一种方法:
map( (.mount
| if . == "/" then "root"
elif . == "/opt" then "opt"
else "tmp" end) as $type
| {key: "val1",
mnt: "\(.mount)-\($type)FS",
key3: {key4: "val4"}} )
我有以下 json 文档 (file.json):
[{
"mount": "/",
"size": "45G",
"usedperc": "26"
},
{
"mount": "/opt",
"size": "197G",
"usedperc": "20"
},
{
"mount": "/tmp",
"size": "5.0G",
"usedperc": "8"
}]
鉴于此文档,我想转换为具有以下结构的不同文档:
[
{
"key": "val1",
"mnt": "/-rootFS",
"key3": {
"key4": "val4"
}
},
{
"key": "val1",
"mnt": "/opt-optFS",
"key3": {
"key4": "val4"
}
},
{
"key": "val1",
"mnt": "/tmp-tmpFS",
"key3": {
"key4": "val4"
}
}
]
然而,当尝试使用 js 应用转换时,它在文档的第一次迭代时停止,并且不处理文档的其余部分:
jq ' [{
"key":"val1",
"mnt": .[]|(if select(.mount == "/") then "/-rootFS" elif select(.mount == "/opt") then "/opt-optFS" elif select(.mount == "/tmp") then "/tmp-tmpFS" else . end ) ,
"key3":{
"key4": "val4"
}}]' < file.json
#output
[
{
"key": "val1",
"mnt": "/-rootFS",
"key3": {
"key4": "val4"
}
}
]
不知道该怎么做,我尝试了很多不同的方法,主要是遇到“无法使用字符串“mount”索引数组”错误。顺便说一句,这实际上只是一个更大的 jq 表达式的测试用例,所以如果可能的话,我想用 jq 来做
这是一种方法:
map( (.mount
| if . == "/" then "root"
elif . == "/opt" then "opt"
else "tmp" end) as $type
| {key: "val1",
mnt: "\(.mount)-\($type)FS",
key3: {key4: "val4"}} )