本文介绍了jq的意外循环周期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用jq将bash中的表打印到json的stdout中:

I'm trying to print a table in bash to stdout from json with jq:

[
    {
      "key": "name",
      "doc_count": 1000,
      "values_over_time": {
        "buckets": [
          {
            "key_as_string": "2019-05-01 11:00:00.000",
            "key": 1556708400000,
            "doc_count": 50
          },
          {
            "key_as_string": "2019-05-02 12:00:00.000",
            "key": 1556798400000,
            "doc_count": 40
          },
          {
            "key_as_string": "2019-05-02 13:00:00.000",
            "key": 1556802000000,
            "doc_count": 30
          }
        ]
      }
    }
]

使用jq -r '(.[].key + " " + .[].values_over_time[][].key_as_string) + " " + (.[].values_over_time[][].doc_count|tostring)'我得到以下结果:

"name 2019-05-01 11:00:00.000 50"
"name 2019-05-02 12:00:00.000 50"
"name 2019-05-02 13:00:00.000 50"
"name 2019-05-01 11:00:00.000 40"
"name 2019-05-02 12:00:00.000 40"
"name 2019-05-02 13:00:00.000 40"
"name 2019-05-01 11:00:00.000 30"
"name 2019-05-02 12:00:00.000 30"
"name 2019-05-02 13:00:00.000 30"

额外的循环级别有些奇怪,我希望只看到3行:

There is something strange with additional loop level as I expect to see only 3 lines:

"name 2019-05-01 11:00:00.000 50"
"name 2019-05-02 12:00:00.000 40"
"name 2019-05-02 13:00:00.000 30"

阅读jq文档,但无法理解正确整齐地进行正确迭代的正确方法.你有什么线索吗?

Read jq docs but wasn't able to understand the right way to iterate in a proper in a neat way. Do you have any clues?

JQplay代码示例

推荐答案

您将values_over_time扩展了两次,因此生成了3 * 3 = 9个输出.做类似这样的事情:

You're expanding values_over_time twice, thus 3 * 3 = 9 outputs are generated. Do something like this instead:

.[] | .key + " " + (.values_over_time.buckets[] | "\(.key_as_string) \(.doc_count)")

比较这两个命令以清楚地看出差异:

Compare these two commands to see the difference clearly:

$ jq -nc '[1,2,3] | [.[]*.[]]'
[1,2,3,2,4,6,3,6,9]
$ jq -nc '[1,2,3] | [.[]|.*.]'
[1,4,9]

这篇关于jq的意外循环周期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 08:44