Node-RED v3.0.2 string to json

I am new to Node Red and I want to parse the data coming in via serial port, and convert it to JSON format.
The data string I'm getting is from a demo board, and it arrives every one second as follows:

| Hum[%]: 56.00 | Temp[C]: 21.50 | Pres[hPa]: 966.11 | Temp2[C]: 21.30 | Acc[mg]: 10 -25 1030 | Gyr[mdps]: 2170 -3500 1400 | Acc2[mg]: 27 -26 979 | Mag[mGauss]: -4 163 166 |

I would like to be able to form a JSON, with the following format:

{
"hum" : "value",
"temp" : "value",
"pres" : "value",
"acc" : "value",
"gyr" : "value",
"pres" : "value",
"temp_2" : "value",
"acc" : "value",
"gyr" : "value",
"acc_2" : "value",
"mag" : "value",
}

Try this in a function node-

let text = msg.payload.slice(1, -1) //remove outer |
text = text.split("|") //use | as separator

let data = {
    "hum": "value",
    "temp": "value",
    "pres": "value",
    "temp_2": "value",
    "acc": "value",
    "gyr": "value",
    "acc_2": "value",
    "mag": "value",
}

const key=Object.keys(data) // list of keys

for (let index = 0; index < text.length; index++) { //iterate over text
    let element = text[index].split(":"); // split out the value
    data[key[index]] = element[1].trim() //set required key to value without exta spaces
    }

msg.payload= data
return msg;
2 Likes

Thanks for taking the time!
I will test the code.

Regards!

1 Like

Its based on injectiong this -
| Hum[%]: 56.00 | Temp[C]: 21.50 | Pres[hPa]: 966.11 | Temp2[C]: 21.30 | Acc[mg]: 10 -25 1030 | Gyr[mdps]: 2170 -3500 1400 | Acc2[mg]: 27 -26 979 | Mag[mGauss]: -4 163 166 |

I changed the object to match the payload content as your sample object had some duplicates.

Let me know how you get on with it :wink:

1 Like

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