简体   繁体   中英

How can I convert this text to JSON by nodejs?

How can I convert this text to JSON by nodejs?

Input:

---
title:Hello World
tags:java,C#,python
---
## Hello World
```C#
Console.WriteLine(""Hello World"");
```

Expected output:

{
    title:"Hello World",
    tags:["java","C#","python"],
    content:"## Hello World\n```C#\nConsole.WriteLine(\"Hello World\"");\n```"
}

What I've tried to think:

  1. use regex to get key:value array, like below:
---
{key}:{value}
---
  1. then check if key equals tags then use string.split function by , to get tags values array else return value.

  2. other part is content value.

but I have no idea how to implement it by nodejs.

Looks like you're trying to convert markdown to JSON. Take a look at markdown-to-json . You can also use a markdown parser (like markdown-it ) to get tokens out of the text which you'd have to parse further.

In this specific case, if your data is precisely structured like that, you can try this:

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));
});

Then you just wrap the whole fs.readFile in a loop to process multiple inputs. Note that you need each input to be in a separate file and structured EXACTLY the way you mentioned in your question for this to work. For more general usage, probably try some existing npm packages like others suggest so you do not reinvent the wheel.

If the input is in a known format then you should use a battle tested library to convert the input into json especially if the input is extremeley dynamic in nature, otherwise depending on how much dynamic is the input you might be able to build a parser easily.

Assuming the input is of a static structure as you posted then the following should do the work

 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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM