jq,如果字段是带有解析的 JSON 表示形式的字符串,则重新分配字段



我有以下JSON:

[
{
"test": "["example"]"
},
{
"test": ["example2"]
}
]

对于每个对象,我想 1] 检查"test"是否是一个字符串,2] 如果 test 是一个字符串,将其解析为实际的 JSON 数组,然后重新分配它。所以输出将是:

[
{
"test": ["example"]
},
{
"test": ["example2"]
}
]

我尝试了以下代码:map(if .test|type == "string" then .test= .test|fromjson else . end).但是,我收到一个错误,说只能解析字符串。我认为这是因为 jq 认为.test不是字符串,但是,我知道 .test 是一个字符串,因为 if 语句,所以我不确定出了什么问题。

jq 过滤器可以简化为:

map(if .test|type == "string" then .test |= fromjson else . end)

甚至:

map(.test |= if type == "string" then fromjson else . end)

解决方案原来是

map(if .test|type == "string" then .test=(.test|fromjson) else . end)

我猜.test=.test|fromjson困惑的jq

最新更新