【问题标题】:Attribute Syntax for JSON query in check_json.plcheck_json.pl 中 JSON 查询的属性语法
【发布时间】:2018-02-09 21:32:34
【问题描述】:

所以,我尝试在 NagiosXI 中设置 check_json.pl 来监控一些统计数据。 https://github.com/c-kr/check_json

我使用的是code with the modification I submitted in pull request #32,所以行号反映了该代码。

json 查询返回如下内容:

[
    {
        "total_bytes": 123456,
        "customer_name": "customer1",
        "customer_id": "1",
        "indices": [
            {
                "total_bytes": 12345,
                "index": "filename1"
            },
            {
                "total_bytes": 45678,
                "index": "filename2"
            },

        ],
        "total": "765.43gb"
    },
   {
        "total_bytes": 123456,
        "customer_name": "customer2",
        "customer_id": "2",
        "indices": [
            {
                "total_bytes": 12345,
                "index": "filename1"
            },
            {
                "total_bytes": 45678,
                "index": "filename2"
            },

        ],
        "total": "765.43gb"
    }
]

我正在尝试监控特定文件的大小。所以检查应该是这样的:

/path/to/check_json.pl -u https://path/to/my/json -a "SOMETHING" -p "SOMETHING"

...我试图找出一些东西,以便我可以监视 customer2 中 filename1 的 total_bytes,我知道 customer_id 和索引,但不知道它们在各自数组中的位置。

我可以通过使用字符串“[0]->{'total_bytes'}”来监控 customer1 的总字节数,但我需要能够指定哪个客户并深入挖掘文件名(已知)和文件大小(要监控的统计数据)和工作查询给我状态(OK、WARNING 或 CRITICAL)。添加 -p 我得到的都是错误....

-p 的错误,无论我如何表达它总是:

Not a HASH reference at ./check_json.pl line 235.

即使我可以从示例“[0]->{'total_bytes'}”中获得有效的 OK,在 -p 中使用它仍然会给出相同的错误。

指向有关要使用的格式的文档的链接将非常有帮助。脚本的自述文件或 -h 输出中的示例在这里失败了。有什么想法吗?

【问题讨论】:

  • 如果你要标记这篇文章,如果你至少有礼貌地告诉我原因,我将不胜感激。
  • 看来你和原来的 check_json 最大的脱节是原来的期望返回的 JSON 是一个对象,而你的 JSON 是一个对象数组。您的 $json_response 是一个 ARRAY 参考:第 235 行(以及第 229、259、265 行)期望它是一个 HASH 参考。

标签: arrays json perl nagios nagiosxi


【解决方案1】:

我真的不知道你的问题是什么。我确定我并不孤单,因此投了反对票。

一旦你有解码的 json,如果你有一个 customer_id 要搜索,你可以这样做:

my ($customer_info) = grep {$_->{customer_id} eq $customer_id} @$json_response;

关于第 235 行的错误,这看起来很奇怪:

foreach my $key ($np->opts->perfvars eq '*' ? map { "{$_}"} sort keys %$json_response : split(',', $np->opts->perfvars)) {
    # ....................................... ^^^^^^^^^^^^^
    $perf_value = $json_response->{$key};

如果 perfvars eq "*",例如,您似乎正在寻找 $json_reponse->{"{total}"}。您可能想要验证用户的输入:

    die "no such key in json data: '$key'\n" unless exists $json_response->{$key};

将哈希引用查找字符串化的整个业务闻起来很糟糕。

一个更好的问题应该是这样的:

我有这个 JSON 数据。如何获取 id 为 1 的客户的 total_bytes 总和?

https://stackoverflow.com/help/mcve

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-10
    • 2017-03-15
    • 1970-01-01
    • 1970-01-01
    • 2021-10-10
    相关资源
    最近更新 更多