Skip to content

Commit 84878f3

Browse files
Eommmcollina
authored andcommitted
Ignore BOM char (#5)
* add bom test * add bom check
1 parent 7e3df95 commit 84878f3

File tree

2 files changed

+15
-0
lines changed

2 files changed

+15
-0
lines changed

index.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,11 @@ function parse (text, reviver, options) {
1717
const protoAction = options.protoAction || 'error'
1818
const constructorAction = options.constructorAction || 'error'
1919

20+
// BOM checker
21+
if (text && text.charCodeAt(0) === 0xFEFF) {
22+
text = text.slice(1)
23+
}
24+
2025
// Parse normally, allowing exceptions
2126
const obj = JSON.parse(text, reviver)
2227

test.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -363,3 +363,13 @@ test('safeParse', t => {
363363

364364
t.end()
365365
})
366+
367+
test('parse string with BOM', t => {
368+
const theJson = { hello: 'world' }
369+
const buffer = Buffer.concat([
370+
Buffer.from([239, 187, 191]), // the utf8 BOM
371+
Buffer.from(JSON.stringify(theJson))
372+
])
373+
t.deepEqual(j.parse(buffer.toString()), theJson)
374+
t.end()
375+
})

0 commit comments

Comments
 (0)