Search code examples
javascriptservicenow

Javascript to parse string payload into Json


I have a script that extracts the body of an email into a JSON payload, however it is currently returned as a single string:

{"sys_id":"xxxx12121","number":"INC22332132","teams_channel":"[email protected]","message_body": "Incident number: INC0012345\n\nIncident start date/time: 27/07/2020 12:56:59 AEST\n\nServices affected: Service 1\n\nDescription: Service Portal Unavailable\n\nImpact: Customers unable to access Service Portal\n\nCurrent Update: Investgations in progress.\n\nRef:MSG3207258_sCxJ4T6p2y21HH2w4xdS"

Can someone please let me know how I could extract the string elements into separate values e.g.

{
"Incident number" : "INC0012345",
"Incident start date/time" : "27/07/2020 12:56:59 AEST",
"Services affected" : "Service 1",
"Description" : "Service Portal Unavailable"
....
}


Solution

  • You can split the String into lines, and use reduce to build an Object out of these lines:

    const obj = {"sys_id":"xxxx12121","number":"INC22332132","teams_channel":"[email protected]","message_body": "Incident number: INC0012345\n\nIncident start date/time: 27/07/2020 12:56:59 AEST\n\nServices affected: Service 1\n\nDescription: Service Portal Unavailable\n\nImpact: Customers unable to access Service Portal\n\nCurrent Update: Investgations in progress.\n\nRef:MSG3207258_sCxJ4T6p2y21HH2w4xdS"};
    
    const props = obj.message_body.split(/\n+/).reduce((res, line) => {
      const [key, value] = line.split(':').map(str => str.trim());
      if (key && value) {
        res[key] = value;
      }
      return res;
    }, {}); 
    
    console.log(props);