Raghava Reddy
Raghava Reddy

Reputation: 343

KSQL streams - Iterate over a JSON

How to Iterate over a JSON in KSQL streams:

My JSON looks like:

{
   "Obj" {
       "ID" : "1"
    },
    "KeyValues": {
        "Key1": "value1",
        "Key2": "value2",
        "Key3": "value3",
        "Key4": "value4",
        "Key5": "value5",
        "Key6": "value6",
        "Key7": "value7",
        "Key8": "value8",
        "Key9": "value9",
        "Key10": "value10",
            |
            |
            |
            |

        "KeyN": "valueN"
  }
}

How can I get below o/p in KSQL . Need to iterate over JSON object for N elements and list as below.

   ID    KEY              VALUE
----------------------------------    
   1     Key1            value1
   1     Key2            value2
   1     Key3            value3
   1     Key4            value4
   1     Key5            value5
   1     Key6            value6
   1     Key7            value7
   1     Key8            value8
   1     Key9            value9
   1     Key10           value10
   1            |
   1            |
   1            |
   1            |
   1 
   1      KeyN          valueN

Thanks in advance.

Upvotes: 1

Views: 438

Answers (1)

Almog
Almog

Reputation: 741

Seems like a UDTF is the right solution for you. You can see explode as an example of a UDTF that takes in an array and then outputs N rows, one for each element.

The signature for your UDTF would be similar:

@Udtf(schema = "STRUCT<key VARCHAR, value VARCHAR>")
public <T> List<Struct> expandMapEntries(final Map<String, String> input) {
  // output a list of key value pairs as a struct from 'input'
}

Then you can use this UDTF and select the fields from it (something like the below):

CREATE STREAM expanded AS SELECT EXPAND_MAP_ENTRIES(KeyValues) AS keyVals FROM source;
CREATE STREAM flattened AS keyVals->key as `KEY`, keyVals->value AS VALUE FROM expanded;

Let me know if that works for you, and feel free to reach out on the community slack (@almog) - I'm quite interested in this use case.

Upvotes: 1

Related Questions