如何将一串文本消息解析为一个对象
How can I parse a string of text messages into an object
我想将模板字符串中包含的文本消息解析为以下 JS 对象。每条短信都由一个新行分隔,在作者姓名之后有一个冒号。消息的内容还可以包括新行、方括号和冒号。您首选的解决方法是什么?
let string = `[03.12.21, 16:12:52] John Doe: Two questions:
How are you? And is lunch at 7 fine?
[03.12.21, 16:14:30] Jane Doe: Im fine. 7 sounds good.`;
let data = {
"03.12.21, 16:12:52": {
"author": "John Doe",
"content": "Two questions:\nHow are you? And is lunch at 7 fine?"
},
"03.12.21, 16:14:30": {
"author": "John Doe",
"content": "Im fine. 7 sounds good."
},
}; // will be parseString()
function parseString() {
// ?
}
我会将整个字符串分成小块,例如:令字符串 = 日期 + 作者 + 内容。这样就简单多了。或者使用类似 string.split()
像这样?
let string = `[03.12.21, 16:12:52] John Doe: Two questions:
How are you? And is lunch at 7 fine?
[03.12.21, 16:14:30] Jane Doe: Im fine. 7 sounds good.`;
let chunks = string.split(/^\[(\d\d\.\d\d\.\d\d, \d\d\:\d\d\:\d\d)\](.*?):/m);
let data = {};
for (let i = 3; i < chunks.length; i += 3) {
const date = chunks[i - 2];
const author = chunks[i - 1].trim();
const content = chunks[i].trim();
data[date] = {
author,
content,
};
}
console.log(data);
.as-console-wrapper{top:0;max-height:100%!important}
是这样的吗?
function parseMessage(message) {
var messageObj = {};
var messageArray = message.split(" ");
messageObj.command = messageArray[0];
messageObj.args = messageArray.slice(1);
return messageObj;
}
我想将模板字符串中包含的文本消息解析为以下 JS 对象。每条短信都由一个新行分隔,在作者姓名之后有一个冒号。消息的内容还可以包括新行、方括号和冒号。您首选的解决方法是什么?
let string = `[03.12.21, 16:12:52] John Doe: Two questions:
How are you? And is lunch at 7 fine?
[03.12.21, 16:14:30] Jane Doe: Im fine. 7 sounds good.`;
let data = {
"03.12.21, 16:12:52": {
"author": "John Doe",
"content": "Two questions:\nHow are you? And is lunch at 7 fine?"
},
"03.12.21, 16:14:30": {
"author": "John Doe",
"content": "Im fine. 7 sounds good."
},
}; // will be parseString()
function parseString() {
// ?
}
我会将整个字符串分成小块,例如:令字符串 = 日期 + 作者 + 内容。这样就简单多了。或者使用类似 string.split()
像这样?
let string = `[03.12.21, 16:12:52] John Doe: Two questions:
How are you? And is lunch at 7 fine?
[03.12.21, 16:14:30] Jane Doe: Im fine. 7 sounds good.`;
let chunks = string.split(/^\[(\d\d\.\d\d\.\d\d, \d\d\:\d\d\:\d\d)\](.*?):/m);
let data = {};
for (let i = 3; i < chunks.length; i += 3) {
const date = chunks[i - 2];
const author = chunks[i - 1].trim();
const content = chunks[i].trim();
data[date] = {
author,
content,
};
}
console.log(data);
.as-console-wrapper{top:0;max-height:100%!important}
是这样的吗?
function parseMessage(message) {
var messageObj = {};
var messageArray = message.split(" ");
messageObj.command = messageArray[0];
messageObj.args = messageArray.slice(1);
return messageObj;
}