Skip to content

fix: support parsing buffers #13

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 11, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ function parse (text, reviver, options) {
const protoAction = options.protoAction || 'error'
const constructorAction = options.constructorAction || 'error'

if (Buffer.isBuffer(text)) {
text = text.toString()
}

// BOM checker
if (text && text.charCodeAt(0) === 0xFEFF) {
text = text.slice(1)
Expand Down
18 changes: 18 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,14 @@ test('parse', t => {
t.end()
})

t.test('parses buffer', t => {
t.strictEqual(
j.parse(Buffer.from('"X"')),
JSON.parse(Buffer.from('"X"'))
)
t.end()
})

t.test('parses object string (reviver)', t => {
const reviver = (key, value) => {
return typeof value === 'number' ? value + 1 : value
Expand Down Expand Up @@ -373,3 +381,13 @@ test('parse string with BOM', t => {
t.deepEqual(j.parse(buffer.toString()), theJson)
t.end()
})

test('parse buffer with BOM', t => {
const theJson = { hello: 'world' }
const buffer = Buffer.concat([
Buffer.from([239, 187, 191]), // the utf8 BOM
Buffer.from(JSON.stringify(theJson))
])
t.deepEqual(j.parse(buffer), theJson)
t.end()
})