首页 > 解决方案 > 遍历 JSON 数组并记录某些值

问题描述

我需要遍历这个 JSON 数组并记录连接数值,如果它大于 0,然后,如果它大于 0,则记录所有者及其上次断开连接时间并将它们存储以输出到脚本完成后控制台。

我尝试过 for 循环和 while 循环,但无法弄清楚如何记录某些值并在脚本末尾将其他值输出到控制台。

[
  {
    "id" : "123456",
    "owner" : "johndoe",
    "x11-display" : ":9",
    "x11-authority" : "/run/user/1112/dcv/123456.xauth",
    "num-of-connections" : 1,
    "creation-time" : "2019-05-28T14:42:24.027240Z",
    "last-disconnection-time" : "2019-05-30T21:47:36.682935Z"
  },
  {
    "id" : "12345",
    "owner" : "johnsmith",
    "x11-display" : ":5",
    "x11-authority" : "/run/user/user/dcv/12345.xauth",
    "num-of-connections" : 0,
    "creation-time" : "2019-05-14T14:12:14.989287Z",
    "last-disconnection-time" : "2019-05-31T18:58:42.851223Z"
  }
]

我想要的是脚本末尾的摘要,上面写着这样的内容。

用户 $owner 有 $num-of-connections 打开连接并在 $last-disconnection-time 上次断开连接。

仅当连接数大于 0 时,我才想要这个。任何帮助将不胜感激。

标签: jsonbashjq

解决方案


我不知道这是否是您正在寻找的解决方案,因为我不清楚请求的输出,但您可以使用这个单行

jq '.[] | select(."num-of-connections">0) | {"owner": ."owner", "num-of-connections": ."num-of-connections", "last-disconnection-time": ."last-disconnection-time"}' input.json

或这个

jq -r '.[] | select(."num-of-connections">0) | "\(.owner) \(."num-of-connections") \(."last-disconnection-time")"' input.json 

推荐阅读