Can anyone help me with Node.js code to parse a string into an object?

This topic was automatically generated from Slack. You can find the original thread here.

Dangermikeb : Hi All - Does anyone have advise on string parsing into an object? My trigger is giving me the payload information in the form of a long string:

'Event: Air Temperature/Humidity, ATH Event: Humidity Report-on-Change Increase, Temperature: 18.4, Humidity: 90.5, Packet Counter: 7, Protocol Version: 1'

My goal is to extract each value and populate a column in a Google Sheet. So I’ll have columns called Event, ATH Event, Temp, Humidity, Packet Counter, and Protocol version. The first row of the spreadsheet would contain ‘Air Temperature/Humidity’, ‘Humidity Report-on-Change Increase’, 18.4, 90.5, 7, 1. But I am having the hardest time extracting the values from the String. I’ve tried a couple different npm packages that are supposed to convert strings elements into an array, but I can’t get it to work. Any pointers would be appreciated.

Chaim Krause : Split on commas first. Then split on colons second. You will end up with k/v pairs. You can use this to create JSON object. Then use something like json-to-xslx to export to Excel.

Dangermikeb : thank you, Chaim - I was looking at using this function: Query string | Node.js v15.13.0 Documentation Does that look like a good one to use? If you probably surmised, I am a javascript newbie.

Sergey Batishchev : Just to flex my JS muscle a bit, a went ahead and wrote the snippet to parse it:

('Event: Air Temperature/Humidity, ATH Event: Humidity Report-on-Change Increase, Temperature: 18.4, Humidity: 90.5, Packet Counter: 7, Protocol Version: 1').split(",").map(  (pair) => pair.split(":")).reduce( (acc, pair) => (acc[pair[0].trim()] = pair[1].trim(), acc), {})

Sergey Batishchev : Proofing screenshot:

Sergey Batishchev : This might be overwhelming for a beginner (and it is all fit in one line!), but what it is does is simple: full string --> split to array of smaller “Event: Air Temperature/Humidity” --> map to array of name/value pair arrays --> reduce to single result object (and trim leading/trailing whitespaces)

Dangermikeb : Sergey - thank you very much. You’ve earned 1 karma point today. May it return 10x that to you.

Dylan Sather (Pipedream) : Beautiful JS Sergey!

Dylan Sather (Pipedream) : Thanks for always being so helpful

Dangermikeb : Gentlemen - FYI here’s my final workflow. Thanks again for the help, Sergey. pipedreamint_RBS305 - Pipedream