1

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.

Abiram
  • 188
  • 1
  • 1
  • 7
  • I’d investigate how to change the format of the data delivered by Kafka. Because the string you get is rubbish. It’s not parseable. – gnasher729 Sep 16 '21 at 07:35
  • 1
    @gnasher729 as long as the format is documented, it's parseable. It's just not JSON. It may be a proprietary format, but that doesn't prevent it from being parsed, even if it has to be done manually. – k314159 Sep 16 '21 at 07:57

1 Answers1

5

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));
Felix Schütz
  • 1,130
  • 1
  • 12
  • 25