lambdaapache-kafkajsonparser

How to convert a string with equal "=" sign to json in JavaScript


The Following String is returned from Kafka to Lambda Connector.

'{device_id=D_2021_A07, key=tele_metrics, sensor_1=62, sensor_2=23}'

I want to convert this to a valid JSON like this

{
    "device_id": "D_2021_A07",   //String
    "key": "tele_metrics",       //String
    "sensor_1": 62,              //Integer
    "sensor_2": 23               //Integer
}

How can I do that in Javascript.


Solution

  • You can strip the first and last character, split at the commas, split at each =, convert the values to numbers if possible, and then combine the pairs to an object:

    const dataA = '{device_id=D_2021_A07, key=tele_metrics, sensor_1=62, sensor_2=23}';
    const dataB = Object.fromEntries(
      dataA
        .substring(1, dataA.length - 1)
        .split(', ')
        .map(pair => pair.split('='))
        .map(([key, value]) => [key, isNaN(value) ? value : +value])
    );
    console.log(dataB);
    console.log(JSON.stringify(dataB));