与 JQ 的价值图

pag*_*gid 4 json jq

我有一个很大的 JSON 文件,我想在其中基于某种映射来转换一些值。

我拥有的数据如下所示:

[
    {"id":1, "value":"yes"},
    {"id":2, "value":"no"},
    {"id":3, "value":"maybe"}
]
Run Code Online (Sandbox Code Playgroud)

我想将其转换为这样的列表:

[
    {"id":1, "value":"10"},
    {"id":2, "value":"0"},
    {"id":3, "value":"5"}
]
Run Code Online (Sandbox Code Playgroud)

使用固定映射:

yes => 10
no => 0
maybe => 5
Run Code Online (Sandbox Code Playgroud)

我当前的解决方案基于if-elif-else这样的简单组合:

cat data.json| jq '.data[] | .value = (if .value == "yes" then "10" elif .value == "maybe" then "5"  else "0" end)'
Run Code Online (Sandbox Code Playgroud)

But this is really ugly and I'd love to have a more direct way to express the mapping.

Thanks for your help

pea*_*eak 5

如果您想避免在命令行上指定映射,那么以下两种变体可能会令人感兴趣。

第一个变体可与 jq 1.3、jq 1.4 和 jq 1.5 一起使用:

def mapping: {"yes":"10","no":"0","maybe":"5"};
map(.value |=  mapping[.])
Run Code Online (Sandbox Code Playgroud)

下一个变体使用 --argfile 选项(自 jq 1.4 起可用),如果映射对象在文件中可用,则该变体很有趣:

jq --argfile mapping mapping.jq 'map(.value |= $mapping[.])' data.json
Run Code Online (Sandbox Code Playgroud)

最后,在 jq 1.5 中,还可以使用基于导入的其他替代方案(!)。