From aa412972473a35f53617fd92ee3462d8b9808b7b Mon Sep 17 00:00:00 2001 From: Ben Thomson Date: Mon, 7 Aug 2023 16:05:35 +0800 Subject: [PATCH] Minor tweaks to JSON Parser - gonna need a rewrite methinks --- src/utilities/JsonParser.js | 11 +++++++++-- tests/utilities/JsonParser.test.js | 22 ++++++++++++++++++++++ 2 files changed, 31 insertions(+), 2 deletions(-) create mode 100644 tests/utilities/JsonParser.test.js diff --git a/src/utilities/JsonParser.js b/src/utilities/JsonParser.js index 7085516..5807662 100644 --- a/src/utilities/JsonParser.js +++ b/src/utilities/JsonParser.js @@ -15,7 +15,14 @@ import Singleton from '../abstracts/Singleton'; */ export default class JsonParser extends Singleton { parse(str) { - const jsonString = this.parseString(str); + let jsonString; + + try { + jsonString = this.parseString(str); + } catch (e) { + return str; + } + return JSON.parse(jsonString); } @@ -94,7 +101,7 @@ export default class JsonParser extends Singleton { /* * object */ - if (str[0] === '{') { + if (str[0] === '{' || (this.canBeKeyHead(str[0]) && str.indexOf(':') !== -1)) { type = 'needKey'; key = null; result = '{'; diff --git a/tests/utilities/JsonParser.test.js b/tests/utilities/JsonParser.test.js new file mode 100644 index 0000000..77ada75 --- /dev/null +++ b/tests/utilities/JsonParser.test.js @@ -0,0 +1,22 @@ +import TestInstance from '../../src/main/Snowboard'; + +describe('JsonParser utility', () => { + beforeEach(() => { + document.currentScript.dataset.baseUrl = 'https://example.com'; + document.currentScript.dataset.assetUrl = 'https://example.com/fixtures/assets/'; + + window.Snowboard = new TestInstance(); + }); + + it('parses a null or undefined', () => { + expect(Snowboard.jsonParser().parse('null')).toEqual(null); + expect(Snowboard.jsonParser().parse('undefined')).toBeUndefined(); + }); + + it('parses a simple string', () => { + expect(Snowboard.jsonParser().parse('test')).toEqual('test'); + expect(Snowboard.jsonParser().parse('"test"')).toEqual('test'); + expect(Snowboard.jsonParser().parse('"null"')).toEqual('null'); + expect(Snowboard.jsonParser().parse('\'test\'')).toEqual('test'); + }); +});