Skip to content

Commit

Permalink
Minor tweaks to JSON Parser - gonna need a rewrite methinks
Browse files Browse the repository at this point in the history
  • Loading branch information
bennothommo committed Aug 7, 2023
1 parent d198bb9 commit aa41297
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
11 changes: 9 additions & 2 deletions src/utilities/JsonParser.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

Expand Down Expand Up @@ -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 = '{';
Expand Down
22 changes: 22 additions & 0 deletions tests/utilities/JsonParser.test.js
Original file line number Diff line number Diff line change
@@ -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');
});
});

0 comments on commit aa41297

Please sign in to comment.