Skip to content

Commit

Permalink
feat(bom): allow processing of json files with BOM
Browse files Browse the repository at this point in the history
  • Loading branch information
jonluca committed Mar 6, 2024
1 parent f9e83c0 commit 781c26f
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
16 changes: 16 additions & 0 deletions lib/parsers/json.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,11 @@ export default {
*/
canParse: ".json",

/**
* Allow JSON files with byte order marks (BOM)
*/
allowBOM: true,

/**
* Parses the given file as JSON
*/
Expand All @@ -37,6 +42,17 @@ export default {
try {
return JSON.parse(data);
} catch (e: any) {
if (this.allowBOM) {
try {
// find the first curly brace
const firstCurlyBrace = data.indexOf("{");
// remove any characters before the first curly brace
data = data.slice(firstCurlyBrace);
return JSON.parse(data);
} catch (e: any) {
throw new ParserError(e.message, file.url);
}
}
throw new ParserError(e.message, file.url);
}
}
Expand Down
7 changes: 7 additions & 0 deletions lib/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,13 @@ export interface Plugin {
*/
allowEmpty?: boolean;

/**
* Specifies whether a Byte Order Mark (BOM) is allowed or not. Only applies to JSON parsing
*
* @type {boolean} @default true
*/
allowBOM?: boolean;

/**
* The encoding that the text is expected to be in.
*/
Expand Down

0 comments on commit 781c26f

Please sign in to comment.