1

today i'd like to translate a text to json data

exemple :

1    kokoa#0368's Discord Profile Avatar    kokoa#0000    826
2    Azzky 陈东晓#7475's Discord Profile Avatar    Azzky 陈东晓#0000    703
3    StarKleey 帅哥#6163's Discord Profile Avatar    StarKleey 帅哥#0000    640

to =>

{
 "kokoa#0000": "826",
 "Azzky 陈东晓#0000": "703",
 "StarKleey 帅哥#0000": "640"
}

for the moment i have this one :

fs.appendFile(`./Text/mess.txt`, `${body.replace(/s Discord Profile Avatar/g, '').split(/[\n \t ' ']/)}`, function (err) {

So the result is this one =>

1,kokoa#0368,,kokoa#0000,826
2,Azzky 陈东晓#7475,,Azzky 陈东晓#0000,703
3,StarKleey 帅哥#6163,,StarKleey 帅哥#0000,640

But i would like delete firsts numbers, delete the duplicate array and make this one on .json

Someone know how can i do this ? And if i need new method to make this one, it's not a problem.

Thank you.

StarKleey
  • 49
  • 1
  • 8

1 Answers1

0

You can read file line by line and convert each line to a 2-elements array with key and value. For example, first line can be converted to:

['kokoa#0000','826']

As you can se 0 index is a key and 1 index is a value. When you convert all lines to this kind of array you can reduce it to an object and convert it to JSON.

See example method:

function convertLinesToJson(lines) {
    const dpaText = "Discord Profile Avatar";
    const jsonObject = lines
        //only with 'Discord ...' text
        .filter(line => line.includes(dpaText))
        //get what is after 'Discord ...' text and split into 2-elements array
        .map(line => {
            const index = line.indexOf(dpaText) + dpaText.length;
            const keyValue = line.substr(index).trim().split(/[ ]{4}/);
            return keyValue;
        })
        // convert [key, value] array into an object
        .reduce((accumulator, currentValue) => {
            accumulator[currentValue[0]] = currentValue[1];
            return accumulator;
        }, {});

    //convert object to JSON
    return JSON.stringify(jsonObject);
}

Usage:

let lines = [
    "1    kokoa#0368's Discord Profile Avatar    kokoa#0000    826",
    "2    Azzky 陈东晓#7475's Discord Profile Avatar    Azzky 陈东晓#0000    703",
    "3    StarKleey 帅哥#6163's Discord Profile Avatar    StarKleey 帅哥#0000    640"
];
const json = convertLinesToJson(lines);
console.log(json);

Above example code prints:

{"kokoa#0000":"826","Azzky 陈东晓#0000":"703","StarKleey 帅哥#0000":"640"}

See also:

Michał Ziober
  • 37,175
  • 18
  • 99
  • 146
  • 1
    I'm back. I have a little problem, when i put my **body** in `let lines = [body]` the result is : `{} `. – StarKleey Oct 10 '20 at 14:29
  • @StarKleey, your `body` should be a lines from a text files. If you read the whole file you need to split it by new line character and this is how you get your lines. Or take a look on linked question where it is shown how to read file line by line. – Michał Ziober Oct 10 '20 at 16:07