遍历JSON数组并记录某些值

时间:2019-06-04 14:48:18

标签: json bash jq

我需要遍历此JSON数组并记录连接数num(如果它大于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时,我才需要这样做。非常感谢您的帮助。

3 个答案:

答案 0 :(得分:0)

我不知道这是否是您正在寻找的解决方案,因为请求的输出对我来说还不清楚,但是您可以采用这种单线排列

//this is my book combo model that returns books into combobox

public class BookComboBoxModel extends AbstractListModel<Book> implements ComboBoxModel<Book> {

    private List <Book> data;
    private Book selectedItem;


    public BookComboBoxModel(List<Book> data) {
        this.data = data;
    }

    public BookComboBoxModel() {
    }

    public void add(List<Book> data) {
        this.data = data;
    }

    @Override
    public int getSize() {
        return data.size();
    }

    @Override
    public Book getElementAt(int index) {
        return data.get(index);
    }

    @Override
    public void setSelectedItem(Object anItem) {
        selectedItem = (Book) anItem;
    }

    @Override
    public Object getSelectedItem() {
        return selectedItem;
    }
}

或这个

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

答案 1 :(得分:0)

也许是吗?

jq -r '.[] | select(."num-of-connections" > 0) | "User \(.owner) has \(."num-of-connections") open connections and last disconnected at \(."last-disconnection-time")."' test.json

将在您固定的样本数据上打印出来:

User johndoe has 1 open connections and last disconnected at 2019-05-30T21:47:36.682935Z.

答案 2 :(得分:0)

如果对替代解决方案感兴趣,可以采用一种新颖的方法来实现这一点-使用基于步行路径的unix实用程序 jtc ,其中逻辑大部分被编码为JSON树:

bash $ <file.json jtc -w'[:][num-of-connections]:<^[^0]>D[-1][owner]<o>v[-1][last-disconnection-time]' -T'"user {o} has {$0} open connections and last disconnected at {}"' -qq
user johndoe has 1 open connections and last disconnected at 2019-05-30T21:47:36.682935Z
bash $ 

PS>披露:我是jtc-用于JSON操作的shell cli工具的创建者