【问题标题】:JQ duplicate results in output jsonJQ在输出json中重复结果
【发布时间】:2021-12-26 09:07:41
【问题描述】:

我有以下 jq 的输入 json:

{
  "records": [
    {
      "uuid": "14e20b5a-6619-11ec-a838-0050568168f7",
      "nas": {
        "path": "/data/nlp/datasets/ds0"
      }
    },
    {
      "uuid": "799ce816-656c-11ec-a838-0050568168f7",
      "nas": {
        "path": "/data/nlp/datasets/ds1"
      }
    }
  ]
}

下面jq重复结果的原因是什么:

[{junction:.records[].nas.path}+{uuid:.records[].uuid}]

结果:

[
  {
    "junction": "/data/nlp/datasets/ds0",
    "uuid": "14e20b5a-6619-11ec-a838-0050568168f7"
  },
  {
    "junction": "/data/nlp/datasets/ds1",
    "uuid": "14e20b5a-6619-11ec-a838-0050568168f7"
  },
  {
    "junction": "/data/nlp/datasets/ds0",
    "uuid": "799ce816-656c-11ec-a838-0050568168f7"
  },
  {
    "junction": "/data/nlp/datasets/ds1",
    "uuid": "799ce816-656c-11ec-a838-0050568168f7"
  }
]

【问题讨论】:

    标签: jq


    【解决方案1】:

    {junction:.records[].nas.path} 和 {uuid:.records[].uuid} 都产生一个由两个对象组成的流,每个对象都是由 .records[] 引起的迭代引起的。将笛卡尔积相加,总共有四个对象。

    如果你想迭代一次jut,就先把迭代器.records[]拉出来,为后面的过滤器定义一个通用的输入上下文:

    .records[] | {junction:.nas.path} + {uuid:.uuid}
    

    这可以进一步简化为

    .records[] | {junction:.nas.path, uuid}
    
    {
      "junction": "/data/nlp/datasets/ds0",
      "uuid": "14e20b5a-6619-11ec-a838-0050568168f7"
    }
    {
      "junction": "/data/nlp/datasets/ds1",
      "uuid": "799ce816-656c-11ec-a838-0050568168f7"
    }
    

    这大概就是你要找的东西。

    Demo

    【讨论】:

    • 在(整个)过滤器周围加上括号[…],以将两个对象的输出流转换为两个对象的数组:[.records[] | {junction:.nas.path, uuid}]。
    猜你喜欢
    • 2018-08-26
    • 2018-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-24
    • 2014-01-09
    • 1970-01-01
    • 2021-02-15
    相关资源
    最近更新 更多