简体   繁体   English

如何在 jq 中引用 object 上的动态键?

[英]How can I reference dynamic keys on an object in jq?

I'm trying to define some custom filter functions and one thing I need to be able to do is pass a list of strings to a filter and get the corresponding values of the input object.我正在尝试定义一些自定义过滤器函数,我需要做的一件事是将字符串列表传递给过滤器并获取输入 object 的相应值。 For example:例如:

jq -n '{name: "Chris", age: 25, city: "Chicago"} | myFilter(["name", "age"])'

should return:应该返回:

{"name": "Chris", "age": 25} . {"name": "Chris", "age": 25}

I know I can use .[some_string] to dynamically get a value on an object for a specific string key, but I don't know how to utilize this for multiple string keys.我知道我可以使用.[some_string]在 object 上动态获取特定字符串键的值,但我不知道如何将其用于多个字符串键。 I think the problem I'm running into is that jq by default iterates over objects streamed into a filter, but doesn't give a way to iterate over an argument to that filter, even if I use def myFilter($var) syntax that the manual recommends for value-argument behavior .我认为我遇到的问题是 jq 默认情况下迭代流入过滤器的对象,但没有提供迭代该过滤器参数的方法,即使我使用def myFilter($var)语法该手册建议使用value-argument behavior

You could easily define your myFilter using reduce :您可以使用reduce轻松定义myFilter

def myFilter($keys):
  . as $in
  | reduce $keys[] as $k (null; . + {($k): $in[$k]} );

More interestingly, if you're willing to modify your "Query By Example" requirements slightly, you can simply specify the keys of interest in braces, as illustrated by this example:更有趣的是,如果您愿意稍微修改“按示例查询”的要求,您可以简单地在大括号中指定感兴趣的键,如下例所示:

jq -n '{name: "Chris", age: 25, city: "Chicago"} | {name, age}'

If any of the keys cannot be specified in this abbreviated format, simply double-quote them.如果不能以这种缩写格式指定任何键,只需将它们用双引号引起来。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM