Error creating new field with the valu of a nested field

Hello!

im reciving a json with the next format:

    "field": [
      {
        "context": "CONTEXTLESS",
        "value": "x",
        "key": "subfield1"
      },
      {
        "context": "CONTEXTLESS",
        "value": "y",
        "key": "subfield2"
      },
      {
        "context": "CONTEXTLESS",
        "value": "z",
        "key": "subfield3"
      }`

im trying to change it to key:value format with this code:

  if  [field.key] == ["x"]{
    mutate{
      add_field => { "%{[field][key]}" => "%{[field]{value]}"}
    }
  }

but it only works if i put something like:


  if  [field.key] == ["x"]{
    mutate{
      add_field => { "%{[field][key]}" => "%{[field][0][value]}"}
    }
  }

does anyone have an idea?

Thank you in advanced!

That should be [field][key] == "subfield1".

1 Like

Hi badger!

Thanks for answering me . Finally i was able to do it with this ruby ​​code:

    ruby {
      code => "
        event.get('[topField]').each do |item|
            event.set('[newField]['+item['key']+']', item['value'])
       end
      "
    }

this ruby code converts

topField{
  {
    "key": "field",
    "value": "value"
  }
}

to

{ "newField.key.keyword": "value" }

sometimes I get the following error:

[ERROR][logstash.filters.ruby    ] Ruby exception occurred: undefined method `each' for nil:NilClass 

does this occur when an empty value is entered?

It happens if [topField] does not exist. You could change the ruby code to be

code => '
    topField = event.get("[topField]")
    if topField
        topField.each { |item|
            event.set("[newField][#{item['key']}]", item["value"])
        }
    end
'

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.