Javascript 将字符串有效负载解析为 Json
Javascript to parse string payload into Json
我有一个脚本可以将电子邮件的正文提取到 JSON 有效负载中,但是它目前作为单个字符串返回:
{"sys_id":"xxxx12121","number":"INC22332132","teams_channel":"werqwefasdfasdfasd@thread.tacv2","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"
谁能告诉我如何将字符串元素提取为单独的值,例如
{
"Incident number" : "INC0012345",
"Incident start date/time" : "27/07/2020 12:56:59 AEST",
"Services affected" : "Service 1",
"Description" : "Service Portal Unavailable"
....
}
您可以将字符串拆分为多行,然后使用reduce
从这些行中构建一个对象:
const obj = {"sys_id":"xxxx12121","number":"INC22332132","teams_channel":"werqwefasdfasdfasd@thread.tacv2","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);
我有一个脚本可以将电子邮件的正文提取到 JSON 有效负载中,但是它目前作为单个字符串返回:
{"sys_id":"xxxx12121","number":"INC22332132","teams_channel":"werqwefasdfasdfasd@thread.tacv2","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"
谁能告诉我如何将字符串元素提取为单独的值,例如
{
"Incident number" : "INC0012345",
"Incident start date/time" : "27/07/2020 12:56:59 AEST",
"Services affected" : "Service 1",
"Description" : "Service Portal Unavailable"
....
}
您可以将字符串拆分为多行,然后使用reduce
从这些行中构建一个对象:
const obj = {"sys_id":"xxxx12121","number":"INC22332132","teams_channel":"werqwefasdfasdfasd@thread.tacv2","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);