如何将jq的值行转换为JSON输出?

2024-04-26 14:22:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个从我的网络服务器获取顶级IP。试图返回一个JSON对象,该对象显示在本文底部。是否有一种简单的转换方式,可以将行转换为jq创建字符串数组所需的格式

ips=$(cat /var/log/nginx/access.log | cut -d' ' -f1 | sort | uniq -c | sort -nr | head -n 5 | cut -d' ' -f8)

结果:

192.168.1.2
192.168.1.3
192.168.1.5
192.168.1.6
192.168.1.7

我的预期产出是:

"192.168.1.2" "192.168.1.3" "192.168.1.5" "192.168.1.6" "192.168.1.7"

我可能会在这方面做很多工作。我所拥有的是,这个输出与其他一些值一起进入json文件的jq

单个值工作正常,但解析topipsis列表时遇到了麻烦

jq -n --arg stat fails --arg count $count  '[{"stat":$stat,"count": $count},{"liststat": "topips",items: $ARGS.positional }]' --args ${ips[@]}

预期结果如下:

{
"topip": ["10.10.20.9","10.10.10.24","10.10.10.26","10.10.10.28","10.10.10.121","192.168.1.152","172.169.10.21","112.10.10.2","10.10.10.21","10.10.10.21"],
"logins":66,
"visits":75,
"errors":1759
}

Tags: 对象ip网络服务器logjsoncount方式
1条回答
网友
1楼 · 发布于 2024-04-26 14:22:14

让我们从问题描述中的文本行开始:

192.168.1.2
192.168.1.3
192.168.1.5
192.168.1.6
192.168.1.7

如果count=0,那么如果将这些行导入jq程序的此变体中:

jq -nR  arg stat fails  arg count $count  '
  [{$stat,$count},
   {liststat: "topips",
    items: [inputs]}]'

您将获得如下所示的输出。您应该能够根据自己的要求修改此示例。很有可能,您可以单独使用jq高效地实现所需的输出(即,不使用jq中显示的任何中间步骤)

输出

[
  {
    "stat": "fails",
    "count": "0"
  },
  {
    "liststat": "topips",
    "items": [
      "192.168.1.2",
      "192.168.1.3",
      "192.168.1.5",
      "192.168.1.6",
      "192.168.1.7"
    ]
  }
]

相关问题 更多 >