JSON.parse(Buffer) works! Is that true?

7,443 views
Skip to first unread message

Chethiya Abeysinghe

unread,
Feb 3, 2016, 4:28:10 PM2/3/16
to nodejs
Following works in nodejs 4.2.3. But I don't see any documentation saying JSON.parse() accepts a buffer. Is this behavior guaranteed but not documented oris there something I'm doing wrong? 

o = {"tes": 1, "4 byte utf8": "𠜎 𠜱 𠝹 𠱓"};    // { tes: 1, '4 byte utf8': '𠜎 𠜱 𠝹 𠱓' }
buffer = new Buffer(JSON.stringify(o), 'utf8');  // <Buffer 7b 22 74 65 73 22 3a 31 2c 22 34 20 62 79 74 65 20 75 74 66 38 22 3a 22 f0 a0 9c 8e 20 f0 a0 9c b1 20 f0 a0 9d b9 20 f0 a0 b1 93 22 7d>
JSON.parse(buffer);       // { tes: 1, '4 byte utf8': '𠜎 𠜱 𠝹 𠱓' }

Thanks

Andrey

unread,
Feb 3, 2016, 10:58:24 PM2/3/16
to nodejs
Its converted to string first, see spec at http://www.ecma-international.org/ecma-262/5.1/#sec-15.12.2

For example, this results in [1, 2, 3] array :

> var qqq = {}
undefined
> qqq.toString = function () { return "[1, 2, 3]"; }
[Function]
> JSON.parse(qqq)

By default, its "return string using buffer bytes and interpreting them as utf8 sequence"
Reply all
Reply to author
Forward
0 new messages