Home > OS >  Js ".toJSON()" giving a "Buffer" (?) instead of json data
Js ".toJSON()" giving a "Buffer" (?) instead of json data

Time:08-13

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
  ]
}

CodePudding user response:

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.from(fs.readFileSync("./data.json", 'utf-8')); // utf-8 & JSON.from 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);
}

CodePudding user response:

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")
  • Related