Parse JSON array with nested objects

Hi there! I am receiving an array of nested JSON elements and I would like to build a logic capable of transforming the following input

{
  "devices": [
    {
      "device": {
        "device_name": "printer_1",
        "other_field1": "abc",
        "other_field2": "def"
      },
      "category": {
        "category_name": "printers",
        "other_field3": "ghi",
        "other_field4": "jkl"
      },
      "device_id": "1234567890"
    },
    {
      "device": {
        "device_name": "printer_2",
        "other_field1": "abc",
        "other_field2": "def"
      },
      "category": {
        "category_name": "printers",
        "other_field3": "ghi",
        "other_field4": "jkl"
      },
      "device_id": "0987654321"
    },
    {
      "device": {
        "device_name": "laptop_1",
        "other_field1": "abc",
        "other_field2": "def"
      },
      "category": {
        "category_name": "laptops",
        "other_field3": "ghi",
        "other_field4": "jkl"
      },
      "device_id": "2468013579"
    }
  ]
}

in this output:

{
    "printers": ["printer_1", "printer_2"],
    "laptops": ["laptop_1"]
}

Thanks!

You will need to use a ruby filter

    ruby {
        code => '
            devices = event.get("devices")
            if devices
                devices.each { |x|
                    dev = x["device"]["device_name"]
                    cat = x["category"]["category_name"]
                    catValue = event.get(cat)
                    if catValue
                        event.set(cat, catValue << dev)
                    else
                        event.set(cat, [ dev ])
                    end
                }
            end
        '
    }

will produce

  "printers" => [
    [0] "printer_1",
    [1] "printer_2"
],
   "laptops" => [
    [0] "laptop_1"
]

Thanks, @Badger. That was exactly what I am looking for.
Appreciate your help.

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