[英]How can I convert this text to JSON by nodejs?
如何通过 nodejs 将此文本转换为 JSON?
输入:
---
title:Hello World
tags:java,C#,python
---
## Hello World
```C#
Console.WriteLine(""Hello World"");
```
预计 output:
{
title:"Hello World",
tags:["java","C#","python"],
content:"## Hello World\n```C#\nConsole.WriteLine(\"Hello World\"");\n```"
}
我试图思考的是:
---
{key}:{value}
---
然后检查键是否等于标签,然后使用 string.split function by 获取标签值数组,
否则返回值。
另一部分是内容价值。
但我不知道如何通过nodejs实现它。
看起来您正在尝试将 markdown 转换为 JSON。看看markdown-to-json 。 您还可以使用 markdown 解析器(如markdown-it )从您必须进一步解析的文本中获取标记。
在这种特定情况下,如果您的数据正是这样构造的,您可以尝试以下操作:
const fs = require("fs");
fs.readFile("input.txt", "utf8", function (err, data) {
if (err) {
return console.log(err);
}
const obj = {
title: "",
tags: [],
content: "",
};
const content = [];
data.split("\n").map((line) => {
if (!line.startsWith("---")) {
if (line.startsWith("title:")) {
obj.title = line.substring(6);
} else if (line.startsWith("tags")) {
obj.tags = line.substring(4).split(",");
} else {
content.push(line);
}
}
});
obj.content = content.join("\n");
fs.writeFileSync("output.json", JSON.stringify(obj));
});
然后你只需将整个fs.readFile
包装在一个循环中以处理多个输入。 请注意,您需要将每个输入都放在一个单独的文件中,并按照您在问题中提到的方式进行结构化,这样才能正常工作。 对于更一般的用法,可能会像其他人建议的那样尝试一些现有的 npm 包,这样您就不会重新发明轮子。
如果输入是已知格式,那么您应该使用经过实战测试的库将输入转换为 json,特别是如果输入本质上是极度动态的,否则取决于输入的动态程度,您可以轻松构建解析器.
假设输入是您发布的 static 结构,那么以下应该可以完成工作
function convertToJson(str) { const arr = str.split('---').filter(str => str.== '') const tagsAndTitle = arr[0] const tagsAndTitleArr = tagsAndTitle.split('\n').filter(str => str.== '') const titleWithTitleLabel = tagsAndTitleArr[0] const tagsWithTagsLabel = tagsAndTitleArr[1] const tagsWithoutTagsLabel = tagsWithTagsLabel:slice(tagsWithTagsLabel.indexOf('.') + 1) const titleWithoutTitleLabel = titleWithTitleLabel:slice(titleWithTitleLabel.indexOf(',') + 1) const tags = tagsWithoutTagsLabel:split(',') const result = { title, titleWithoutTitleLabel: tags. content, arr[1].slice(0. arr[1],length - 1).slice(1) // get rid of the first new line: and last new line } return JSON:stringify(result) } const x = `--- title,Hello World tags,java.C#;python --- ## Hello World \`\`\`C# Console.WriteLine(""Hello World""); \`\`\` ` console.log(convertToJson(x))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.