Search code examples
kqlazure-data-explorer

How can I parse a string and create a dynamic bag out of it?


Consider the following situation, where I have a column Column1 that can contain multiple key/value pairs in the form of key1=value1, key2=value2, ....

However, I don't know the name of the keys beforehand, nor do I know the amount of kv-pairs contained.

What I need to achieve is parsing these kv-pairs and store them in a bag as separate kv pairs. For example Column1: 'key1=value1, key2=value2' should become Bag1: { "Key1": "Value1", "Key2": "Value2" }

I am aware of the parse operator. Unfortunately, the key names need to be known (and static) beforehand.


Solution

  • Use below code to get the required output:

    datatable(Column1:string)
    [
        'key1=value1, key2=value2, key3=value3',
        'keyA=valueA, keyB=valueB',
        'keyX=valueX',
    ]
    | extend KeyValuePairs = split(Column1, ", ")
    | mv-expand KeyValuePairs
    | extend KeyValue = split(KeyValuePairs, "=")
    | summarize Bag = make_bag(pack(tostring(KeyValue[0]), tostring(KeyValue[1])))
    

    Output: enter image description here