JQ的价值图 [英] Value map with JQ

查看:124
本文介绍了JQ的价值图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很大的JSON文件,我想根据某种映射来转换一些值.

I've a large JSON file where I'd like to transform some values based on some kind of mapping.

我的数据如下:

[
    {"id":1, "value":"yes"},
    {"id":2, "value":"no"},
    {"id":3, "value":"maybe"}
]

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

And I'd like to transform that into a list like this:

[
    {"id":1, "value":"10"},
    {"id":2, "value":"0"},
    {"id":3, "value":"5"}
]

具有固定的映射:

yes => 10
no => 0
maybe => 5

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

My current solution is based on a simple if-elif-else combination like this:

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

但这确实很丑陋,我希望有一种更直接的方式来表示映射.

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

感谢您的帮助

推荐答案

如果希望避免在命令行上指定映射,则可能需要关注以下两个变体.

If one wants to avoid having to specify the mapping on the command line, then the following two variants may be of interest.

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

The first variant can be used with jq 1.3, jq 1.4 and jq 1.5:

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

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

The next variant uses the --argfile option (available since jq 1.4), and is of interest if the mapping object is available in a file:

jq --argfile mapping mapping.jq 'map(.value |= $mapping[.])' data.json

最后,在jq 1.5中,还提供了其他基于 import 的替代方法(!).

Finally, in jq 1.5, other alternatives based on import are also available (!).

这篇关于JQ的价值图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆