0

I have the following NodeJS code:

const msg = Buffer.from([ 34, 115, 106, 100, 104, 34 ]);
const a = JSON.parse(msg.toString('utf-8'))
console.log(a);

The msg buffer is basically the string "sjdh" when using .toString('utf-8') on it.
How come when I run this, JSON.parse is able to parse what is essentially the string "sjdh" and returns it as a result to a?

1 Answers1

1

Some types are allowed to not be wrapped in an object or array by JSON.parse

Read more here What is the minimum valid JSON?

console.log(JSON.parse('"asdad"'))
console.log(JSON.parse('null'))
Konrad
  • 21,590
  • 4
  • 28
  • 64
  • I see! Interesting, so it treats it as a single JSON string which is why it's valid. Well then how should I avoid this? Remove the " characters after using .toString()? – HarelDanieli Feb 23 '23 at 15:33
  • 1
    https://stackoverflow.com/a/3710506 you can also just check after parsing if it's an array or object – Konrad Feb 23 '23 at 15:38