d3x0r / JSON6

JSON for Humans (ES6)
Other
236 stars 14 forks source link

parse should coerce value to a string if it isn't. #5

Closed jdalton closed 6 years ago

jdalton commented 6 years ago

Hi @d3x0r!

Thank you for JSON6 :yum:! I tried to pass a file buffer to JSON6.parse and it didn't coerce to a string like with JSON.parse.

d3x0r commented 6 years ago

https://stackoverflow.com/questions/41951307/convert-a-json-object-to-buffer-and-buffer-to-json-object-back

var temp = JSON.parse(buf.toString());

Or do you expect a result more like 'Convert a Buffer to JSON' in this article? https://hackernoon.com/https-medium-com-amanhimself-converting-a-buffer-to-json-and-utf8-strings-in-nodejs-2150b1e3de57

What sort of buffer? Do you have an example code?

jdalton commented 6 years ago

It's a buffer from fs.readFileSync(filePath). I could pass an encoding "utf8" but expected parse to coerce as builtin JSON.parse. The easiest way for you to support it is to add the following check:

if (typeof msg !== "string") {
  msg = String(msg)
}

This should tackle it and avoid issue with things like symbols too. The String() constructor avoids issues with symbols that msg + "" would have.

d3x0r commented 6 years ago

Okay updated, pushed and published.

jdalton commented 6 years ago

Thank you @d3x0r. That fixed it!