简体   繁体   English

尝试使用 jq 过滤数组 output

[英]Trying to filter an array output with jq

I have the given input as such:我有这样的给定输入:

 [{ "ciAttributes": { "entries": "{\"hostname-cdc1.website.com\":[\"127.0.0.1\"],\"hostname-cdc1-extension.website.com\":[\"127.0.0.1\"]}" }, "ciAttributes": { "entries": "{\"hostname-dfw1.website.com\":[\"127.0.0.1\"],\"hostname-dfw1-extension.website.com\":[\"127.0.0.1\"]}" }, "ciAttributes": { "entries": "{\"hostname-cdc2.website.com\":[\"127.0.0.1\"],\"hostname-cdc2-extension.website.com\":[\"127.0.0.1\"]}" }, "ciAttributes": { "entries": "{\"hostname-dfw2.website.com\":[\"127.0.0.1\"],\"hostname-dfw2-extension.website.com\":[\"127.0.0.1\"]}" }, }]

...and when I execute my jq with the following command (manipulating existing json): ...当我使用以下命令(操作现有的 json)执行我的 jq 时:

jq '.[].ciAttributes.entries | fromjson | keys | [ { hostname: .[0] }] | add' | jq -s '{ instances: . }'

...I get this output: ...我得到这个 output:

 { "instances": [ { "hostname": "hostname-cdc1.website.com" }, { "hostname": "hostname-dfw1.website.com" }, { "hostname": "hostname-cdc2.website.com" }, { "hostname": "hostname-dfw2.website.com" } ] }

My end goal is to only extract "hostnames" that contain "cdc."我的最终目标是只提取包含“cdc”的“主机名”。 I've tried playing with the json select expression but I get a syntax error so I'm sure I'm doing something wrong.我尝试过使用 json select 表达式,但出现语法错误,所以我确定我做错了什么。

First, there is no need to call jq more than once.首先,不需要多次调用 jq 。

Second, because the main object does not have distinct key names, you would have to use the --stream command-line option.其次,因为主 object 没有不同的键名,所以您必须使用 --stream 命令行选项。

Third, you could use test to select the hostnames of interest, especially if as seems to be the case, the criterion can most easily be expressed as a regex.第三,您可以使用test select 感兴趣的主机名,特别是如果似乎是这种情况,标准可以最容易地表示为正则表达式。

So here in a nutshell is a solution:因此,简而言之,这是一个解决方案:

Invocation调用

jq -n --stream -c -f program.jq input.json

program.jq程序.jq

{instances:
 [inputs
 | select(length==2 and (.[0][-2:] == ["ciAttributes", "entries"]))
 | .[-1]
 | fromjson
 | keys_unsorted[]
 | select(test("cdc.[.]"))]}

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

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