1

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.

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

thanks a lot , I upvote this! Like u said , I'd like to convert this format kind markdown to json.
1

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.

2 Comments

i believe this answer will fail if he content itself contained the words title, or tags. Other than that it is quite compact
@ehab It will fail if the content lines start with 'title', 'tags', or '---', otherwise there would not be a problem. But it is definitely only a non reusable code for this one specific case :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.