Splitting Array


#1

I have an array like
"myarray":[{"name":"alice"},{"age":14}]

and i want to split it and put values as in

"dataclass": {

"fields":{

"name":"alice",
"age":14
}

}


(Magnus Bäck) #2

I suspect you need a ruby filter. Something similar to this perhaps?

ruby {
  code => "
    event['myarray'].each { |m|
      m.each_pair { |k, v|
        event['dataclass']['fields'][k] = v
      }
    }
  "
}

#3

showing following error :frowning:
INPUT
alice,22&india,farhan@28#akhtar@34
←**[31mRuby exception occurred: undefined method `[]=' for nil:NilClass {:level=>:**
error}←[0m
{
"message" => [
[0] "alice,22&india,farhan@28#akhtar@34\r"
],
"@version" => "1",
"@timestamp" => "2015-12-03T08:56:58.308Z",
"host" => "myhost",
"age" => "22&india",
"datafields" => "farhan@28#akhtar@34",
"dataclass" => {
"datclassname" => "alice"
},
"myarray" => [
[0] {
"farhan" => 28
},
[1] {
"akhtar" => 34
}
],
"tags" => [
[0] "_rubyexception"
]
}
**my configuration file is **
input {

stdin
{
codec => plain
}
}

filter {

csv {

    columns => ["dataclassname", "age","datafields"]
    separator => ","    
}
mutate
{
rename=>
{
"dataclassname" =>"[dataclass][datclassname]"
 
}
}
ruby {
    code => '
        b = event["datafields"].split("#");
        ary = Array.new;
        for c in b;
            keyvar = c.split("@")[0];
            valuevar = c.split("@")[1];
            d = "{key : " << keyvar << ", value : " << valuevar << "}";
            
            ary.push({ keyvar =>  valuevar.to_i });
            
        end;
        event["myarray"] = ary;
    '
}
ruby {

code => "
event['myarray'].each { |m|
m.each_pair { |k, v|
event['dataclass']['fields'][k] = v
}
}
"
}

}
output {

stdout { codec => rubydebug }
}


(Magnus Bäck) #4

Try inserting

event['dataclass']['fields'] = Hash.new unless event['dataclass'].has_key? 'fields'

before the assignment to make sure that event['dataclass']['fields'] exists and is a hash.


#5

oh magnus ! it worked :smile:
thank you so much !


(system) #6