0

im trying to read the json data from my "data.json" and save the content to a variable called "suggestions", and from that, the sub-sub array with the ["Suggestion x", "randomId"], but it just returns me some weird buffer stuff.

data.json:

[
      [
            ["Suggestion 1", "538033136685285396"],
            ["Suggestion 2", "538033136685285396"],
            ["Suggestion 3", "538033136685285396"],
            ["Suggestion 4", "538033136685285396"],
            ["Suggestion 5", "538033136685285396"],
            ["Suggestion 6", "538033136685285396"],
            ["Suggestion 7", "538033136685285396"],
            ["Suggestion 8", "538033136685285396"]
      ]
]

code:

if (command.toLowerCase().split(" ")[0] === "suggest") {
    const suggestion = command.replace("suggest", "").trim();
    const suggestions = fs.readFileSync("./data.json");
    responseMessage = `
Thank you, for your suggestion! I will review it as soon as possible and get back to you.
> ${command.replace("suggest", "").trim()}
---------------
Suggestions:
${suggestions}
${console.log(suggestions.toJSON())}
      `;
    await message.reply(responseMessage);
}

console return:

{
  type: 'Buffer',
  data: [
    91, 13, 10,  32,  32,  32,  32,  32,  32,  91,  13,  10,
    32, 32, 32,  32,  32,  32,  32,  32,  32,  32,  32,  32,
    91, 34, 83, 117, 103, 103, 101, 115, 116, 105, 111, 110,
    32, 49, 34,  44,  32,  34,  53,  51,  56,  48,  51,  51,
    49, 51, 54,  54,  56,  53,  50,  56,  53,  51,  57,  54,
    34, 93, 13,  10,  32,  32,  32,  32,  32,  32,  93,  13,
    10, 93
  ]
}
1

2 Answers 2

5

The problem is in fs#readFile(Sync): If you don't specify an encoding way, that will be buffer. And you should use JSON#parse instead of toJSON()

if (command.toLowerCase().split(" ")[0] === "suggest") {
    const suggestion = command.replace("suggest", "").trim();
    const suggestions = JSON.parse(fs.readFileSync("./data.json", 'utf-8')); // utf-8 & JSON.parse here.
    responseMessage = `
Thank you, for your suggestion! I will review it as soon as possible and get back to you.
> ${command.replace("suggest", "").trim()}
---------------
Suggestions:
${suggestions}
${console.log(suggestions/*.toJSON()*/)}
      `;
    await message.reply(responseMessage);
}
Sign up to request clarification or add additional context in comments.

Comments

3

As mentioned by @Pointy in comments You need to specify encoding: So, instead of

const suggestions = fs.readFileSync("./data.json");

Specify encoding:

                                                   vvvvvv
const suggestions = fs.readFileSync("./data.json", "utf-8")

Comments

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.