Search code examples
node.jsjsonbuffer

JSON.parse() not failing when it should fail


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?


Solution

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