【问题标题】:Capture array index using jq [duplicate]使用 jq 捕获数组索引 [重复]
【发布时间】:2021-08-24 20:18:56
【问题描述】:

有数据

[
  {
    "name": "test1",
    "id": "id1",
    "ip": "10.0.0.0"
  },
  {
    "name": "test2",
    "id": "id2",
    "ip": "10.1.0.0"
  }
]

我正在尝试使用数组索引捕获一些字段

instances = ( $( echo $data | jq -r '.[] | ("{something to capture index}" + "." + .name + "~" + .id)' ) )

预期输出

1.test1~id1
2.test2~id2

【问题讨论】:

    标签: arrays json shell jq


    【解决方案1】:
    • to_entries 生成一个.key,添加1 以获得所需的“索引”
    • 使用字符串操作 (\()) 防止“"" + "" + ""”垃圾邮件
    to_entries[] | "\(.key + 1).\(.value.name)~\(.value.id)"
    

    jq --raw-output 'to_entries[] | "\(.key + 1).\(.value.name)~\(.value.id)"'
    
    1.test1~id1
    2.test2~id2
    

    JqPlay Demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-16
      • 2023-04-08
      • 1970-01-01
      • 1970-01-01
      • 2013-10-05
      • 2016-07-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多