String with Multiple Lines Convert into an Object

I'm having trouble with this string and converting it into an object so I can eventually push it into a table.

2021-03-22 12:39
W1AW
14200
Example Comment
W1HW

If it was all one string on one line, I'd use the string.str() command to parse through it, but with elements on different lines, I'm not sure how to accomplish this. The 4th line down (example comment) can be a phrase or comment with variable length (usually less then 40 characters) that I'd like to keep the whole comment in tact.

Can someone point me in the right direction?

Kyle

If you want an object...

msg.payload = Object.assign({}, msg.payload.split("\n"));
return msg;

result...

{
  '0': '2021-03-22 12:39',
  '1': 'W1AW',
  '2': '14200',
  '3': 'Example Comment',
  '4': 'W1HW'
}

If you want an array...

msg.payload = msg.payload.split("\n");
return msg;

result...

[ '2021-03-22 12:39', 'W1AW', '14200', 'Example Comment', 'W1HW' ]

If you want an object with named props...

var arr = msg.payload.split("\n");
msg.payload = {
 "prop1": arr[0],
 "prop2": arr[1],
 "prop3": arr[2],
 "comment": arr[3],
 "prop5": arr[4]
}
return msg;

result...

{
  prop1: '2021-03-22 12:39',
  prop2: 'W1AW',
  prop3: '14200',
  comment: 'Example Comment',
  prop5: 'W1HW'
}

a little bit javascript understanding can get you a long way.

1 Like

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