【问题标题】:How to split a JSON array inside an object如何在对象内拆分 JSON 数组
【发布时间】:2015-07-14 09:37:50
【问题描述】:

我有一个 JSON 消息,其中包含一个数组。我想将其拆分为多个事件:

{
"type": "monitor",
"server": "10.111.222.333",
"host": "abc.de",
"bean": [{
    "name": "beanName1",
    "reseted": "2015-06-05T15:10:00.192Z",
    "method": [{
      "name": "getAllXY",
      "count": 5,
      "min": 3,
      "max": 5
    },
    {
      "name": "getName",
      "count": 4,
      "min": 2,
      "max": 4
    }]
  },
  {
    "name": "beanName2",
    "reseted": "2015-06-05T15:10:00.231Z",
    "method": [{
      "name": "getProperty",
      "count": 4,
      "min": 3,
      "max": 3
    }]
  },
  {
    "name": "beanName3",
    "reseted": "2015-06-05T15:10:00.231Z"
  }]
}

使用过滤器拆分“bean”:

input {
  stdin {
    codec => "json"
  }
}

filter {
  split {
    field => "bean"
  }
}

output {
  stdout{codec => "json"}
}

运行良好:

{"type":"monitor",
 "server":"10.111.222.333",
 "host":"abc.de",
 "bean":{
   "name":"beanName1",
   "reseted":"2015-06-05T15:10:00.192Z",
   "method":[{
     "name":"getAllXY",
     "count":5,
     "min":3,
     "max":5 
    },{
     "name":"getName",
     "count":4,
     "min":2,
     "max":4
    }]},
 "@version":"1",
 "@timestamp":"2015-07-14T09:21:18.326Z"
}

{"type":"monitor",
 "server":"10.111.222.333",
 "host":"abc.de",
 "bean":{
   "name":"beanName2",
   "reseted":"2015-06-05T15:10:00.231Z",
   "method":[{
     "name":"getProperty",
     "count":4,
     "min":3,
     "max":3
   }]},
 "@version":"1",
 "@timestamp":"2015-07-14T09:21:18.326Z"
}

    ...

为了也分离“方法”,我添加了另一个拆分过滤器:

  split {
    field => "bean"
  }
  split {
    field => "bean.method"
  }

但那样我只会收到一条错误消息:

filterworker 中的异常 {"exception"=>#LogStash::ConfigurationError: 只有 String 和 Array 类型是可拆分的。 field:bean.method 的类型 = NilClass

我无法访问对象“bean”中的数组“方法”。我尝试了不同的符号,但没有运气。是否可以访问数组,可能还不支持?

【问题讨论】:

    标签: json logstash


    【解决方案1】:

    下面的代码应该做你想做的事情并为每个方法返回一个事件:

    filter {
        if !("splitted_beans" in [tags]) {
            json {
                source => "message"
            }
            split { 
                field => "bean"
                add_tag => ["splitted_beans"]
            }
        }
    
        if ( "splitted_beans" in [tags] and [bean][method] ) {
            split {
                field => "bean[method]"
            }
        }
    }
    

    第二个条件检查第一个方法是否成功以及 bean 中是否存在方法。所以它也适用于没有方法的 bean。

    【讨论】:

    • 它有效,但我有没有方法的bean。所以我添加了 if [bean][method] {... 现在很好了,非常感谢。
    • 完美,我已将[bean][method] 条件添加到我的答案中。
    • @hurb 如果“bean”只有一个元素怎么办?在这种情况下,此代码不起作用
    猜你喜欢
    • 1970-01-01
    • 2018-02-23
    • 1970-01-01
    • 1970-01-01
    • 2014-10-03
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 2015-03-14
    相关资源
    最近更新 更多