我有一个字符串变量 msg.payload 形式的输入,如下所示。
Hi Team,
Below are the details of for the given source platform.
name=abc
status=Active
company=Discovery
FromDate=6/05/2020
ToDate=20/05/2020
Please do the needful ASAP
Thanks & Regards,
xyz
我只想拿
name=abc
status=Active
company=Discovery
FromDate=6/05/2020
ToDate=20/05/2020
忽略其余部分,然后使用 JavaScript 将其转换为 JSON,如
{"name":"abc", "status":"Active","company":"ABCD" ,"FromDate":"6/05/2020","ToDate":"20/05/2020"}
我怎样才能实现它?输入中的所有数据都将采用 key=value 的形式。
最佳答案
您可以利用多个内置 JavaScript 字符串和数组函数。
使用 String.prototype.split() 将输入转换为行数组:
const lines = input.split('\n');
使用 Array.prototype.filter() 过滤掉不包含等号的行:
const kvPairs = lines.filter(line => line.includes('='));
使用Array.prototype.forEach()和 String.prototype.split()加载具有键值属性的对象:
let object = {};
kvPairs.forEach(line => {
[key, val] = line.split('=');
object[key] = val;
});
把它们放在一起:
const input = 'Hi Team,\nBelow are the details of for the given source platform.\nname=abc\nstatus=Active\ncompany=Discovery\nFromDate=6/05/2020\nToDate=20/05/2020\nPlease do the needful ASAP\nThanks & Regards,\nxyz';
const lines = input.split('\n');
const kvPairs = lines.filter(line => line.includes('='));
let object = {};
kvPairs.forEach(line => {
[key, val] = line.split('=');
object[key] = val;
});
console.log('object:', object);
关于javascript - 对文本内容进行过滤,并尝试将过滤后的内容转换为JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61644705/