jq:从对象中选择键的子集 [英] jq: selecting a subset of keys from an object

查看:169
本文介绍了jq:从对象中选择键的子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从数组中输入键的json字符串,返回一个对象,该对象仅包含在原始对象和输入数组中具有键的条目.

Given an input json string of keys from an array, return an object with only the entries that had keys in the original object and in the input array.

我有一个解决方案,但我认为它并不优雅({($k):$input[$k]}感觉特别笨拙……),这是我学习的机会.

I have a solution but I think that it isn't elegant ({($k):$input[$k]} feels especially clunky...) and that this is a chance for me to learn.

jq -n '{"1":"a","2":"b","3":"c"}'   \
    | jq --arg keys '["1","3","4"]' \
    '. as $input 
     | ( $keys | fromjson )
     | map( . as $k
          | $input
          | select(has($k))
          | {($k):$input[$k]}
          )
     | add'

有什么想法要清理吗?

我觉得从嵌套中提取所选属性带有jq 的JSON对象是一个很好的起点,但我无法使其正常工作.

I feel like Extracting selected properties from a nested JSON object with jq is a good starting place but i cannot get it to work.

推荐答案

带内部检查的解决方案:

solution with inside check:

jq 'with_entries(select([.key] | inside(["key1", "key2"])))'

这篇关于jq:从对象中选择键的子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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