From 781c26f21450674e8d83a5a41a784a4b9a50b379 Mon Sep 17 00:00:00 2001 From: JonLuca DeCaro Date: Tue, 5 Mar 2024 20:51:03 -0800 Subject: [PATCH] feat(bom): allow processing of json files with BOM --- lib/parsers/json.ts | 16 ++++++++++++++++ lib/types/index.ts | 7 +++++++ 2 files changed, 23 insertions(+) diff --git a/lib/parsers/json.ts b/lib/parsers/json.ts index aadfd200..85165338 100644 --- a/lib/parsers/json.ts +++ b/lib/parsers/json.ts @@ -21,6 +21,11 @@ export default { */ canParse: ".json", + /** + * Allow JSON files with byte order marks (BOM) + */ + allowBOM: true, + /** * Parses the given file as JSON */ @@ -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); } } diff --git a/lib/types/index.ts b/lib/types/index.ts index 91772c32..4340f78a 100644 --- a/lib/types/index.ts +++ b/lib/types/index.ts @@ -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. */