Skip to content

Commit 781c26f

Browse files
committed
feat(bom): allow processing of json files with BOM
1 parent f9e83c0 commit 781c26f

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

lib/parsers/json.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,11 @@ export default {
2121
*/
2222
canParse: ".json",
2323

24+
/**
25+
* Allow JSON files with byte order marks (BOM)
26+
*/
27+
allowBOM: true,
28+
2429
/**
2530
* Parses the given file as JSON
2631
*/
@@ -37,6 +42,17 @@ export default {
3742
try {
3843
return JSON.parse(data);
3944
} catch (e: any) {
45+
if (this.allowBOM) {
46+
try {
47+
// find the first curly brace
48+
const firstCurlyBrace = data.indexOf("{");
49+
// remove any characters before the first curly brace
50+
data = data.slice(firstCurlyBrace);
51+
return JSON.parse(data);
52+
} catch (e: any) {
53+
throw new ParserError(e.message, file.url);
54+
}
55+
}
4056
throw new ParserError(e.message, file.url);
4157
}
4258
}

lib/types/index.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,13 @@ export interface Plugin {
8888
*/
8989
allowEmpty?: boolean;
9090

91+
/**
92+
* Specifies whether a Byte Order Mark (BOM) is allowed or not. Only applies to JSON parsing
93+
*
94+
* @type {boolean} @default true
95+
*/
96+
allowBOM?: boolean;
97+
9198
/**
9299
* The encoding that the text is expected to be in.
93100
*/

0 commit comments

Comments
 (0)