jq与父级一起获取数组中的每个值 [英] jq get each value in array with parent

查看:35
本文介绍了jq与父级一起获取数组中的每个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像下面的json.我想获得一个输出,其中每个计时器记录包含一行,但包含服务的名称.

I have json that looks like the below. I'd like to get an output that contains one line for each timer record, but includes the name of the service.

{  
   "services":{  
      "service":[  
         {  
            "name":"Test Value",
            "timer":[  
               { "datetime":"08/30/2017 16:33:35", "value":"625" },
               { "datetime":"08/30/2017 16:22:38", "value":"240" }
            ]
         },
         {
            "name":"Test Value 2",
            "timer":[
               { "datetime":"08/30/2017 16:07:38", "value":"432" },
               { "datetime":"08/30/2017 15:59:07", "value":"1355" }
            ]
         }
      ]
   }
}

我想出了.services.service[].name as $name | .services.service[].timer | map([ $name, .datetime, .value ]),这使我

[["Test Value","08/30/2017 16:33:35","625"],["Test Value","08/30/2017 16:22:38","240"]]
[["Test Value","08/30/2017 16:07:38","432"],["Test Value","08/30/2017 15:59:07","1355"]]
[["Test Value 2","08/30/2017 16:33:35","625"],["Test Value 2","08/30/2017 16:22:38","240"]]
[["Test Value 2","08/30/2017 16:07:38","432"],["Test Value 2","08/30/2017 15:59:07","1355"]]

我期望的输出是

[["Test Value","08/30/2017 16:33:35","625"],["Test Value","08/30/2017 16:22:38","240"]]
[["Test Value 2","08/30/2017 16:07:38","432"],["Test Value 2","08/30/2017 15:59:07","1355"]]

但是请注意,服务和定时器集的值都是重复的.我想念什么?

But notice that the values are duplicated for both services and sets of timers. What am I missing?

推荐答案

.services.service[]|[{name,timer:.timer[]}|[.name,.timer[]]]将为您提供预期的输出,

.services.service[]|[{name,timer:.timer[]}|[.name,.timer[]]] will give you your expected output,

.services.service[]|{name,timer:.timer[]}|[.name,.timer[]](无数组聚合)将为每个计时器提供一个结果:

.services.service[]|{name,timer:.timer[]}|[.name,.timer[]] (without array aggregation) will give you one result for each timer:

["Test Value","08/30/2017 16:33:35","625"]
["Test Value","08/30/2017 16:22:38","240"]
["Test Value 2","08/30/2017 16:07:38","432"]
["Test Value 2","08/30/2017 15:59:07","1355"]

您错过的尝试是

表达式exp为$ x | ...表示:对于表达式exp的每个值,请使用整个原始输入并将$ x设置为该值来运行管道的其余部分.因此,其功能就像是一个foreach循环.

The expression exp as $x | ... means: for each value of expression exp, run the rest of the pipeline with the entire original input, and with $x set to that value. Thus as functions as something of a foreach loop.

如果您真的想使用变量,则需要这样做:.services.service[]| .name as $name | .timer | map([ $name, .datetime, .value ])

If you really want to use variables you need to do it like this: .services.service[]| .name as $name | .timer | map([ $name, .datetime, .value ])

这篇关于jq与父级一起获取数组中的每个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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