jq:从对象中选择键的子集

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"])))'