diff --git a/HISTORY.md b/HISTORY.md index 4757012..9fdcf6c 100644 --- a/HISTORY.md +++ b/HISTORY.md @@ -3,6 +3,12 @@ https://github.com/josdejong/jsoneditor +## not yet published, version 7.0.5 + +- Fix #794: fix discrepancy between valid JSON numbers and valid JavaScript + numbers (i.e. `+2` is a valid in JavaScript but not in JSON). + + ## 2019-09-11, version 7.0.4 - Fixed #723: schema error popup and color picker not always fully visible. diff --git a/src/js/util.js b/src/js/util.js index bbbf21d..08b27dc 100644 --- a/src/js/util.js +++ b/src/js/util.js @@ -1330,23 +1330,33 @@ export function sortObjectKeys (object, direction) { * @private */ export function parseString (str) { - const lower = str.toLowerCase() - const num = Number(str) // will nicely fail with '123ab' - const numFloat = parseFloat(str) // will nicely fail with ' ' - if (str === '') { return '' - } else if (lower === 'null') { - return null - } else if (lower === 'true') { - return true - } else if (lower === 'false') { - return false - } else if (!isNaN(num) && !isNaN(numFloat)) { - return num - } else { - return str } + + const lower = str.toLowerCase() + if (lower === 'null') { + return null + } + if (lower === 'true') { + return true + } + if (lower === 'false') { + return false + } + + try { + // will nicely fail for strings like '123ab', ' ', and '+1' + const num = JSON.parse(str) + if (typeof num === 'number' && !isNaN(num)) { + return num + } + } + catch (err) { + // no need to handle this error, it was just to try parsing into a number + } + + return str } /** diff --git a/test/util.test.js b/test/util.test.js index 7f8e77f..8f967d9 100644 --- a/test/util.test.js +++ b/test/util.test.js @@ -393,10 +393,18 @@ describe('util', () => { it('should parse a string', () => { assert.strictEqual(parseString('foo'), 'foo') assert.strictEqual(parseString('234foo'), '234foo') + assert.strictEqual(parseString(' 234'), 234) + assert.strictEqual(parseString('234 '), 234) assert.strictEqual(parseString('2.3'), 2.3) assert.strictEqual(parseString('null'), null) assert.strictEqual(parseString('true'), true) assert.strictEqual(parseString('false'), false) + assert.strictEqual(parseString('+1'), '+1') + assert.strictEqual(parseString(' '), ' ') + assert.strictEqual(parseString(''), '') + assert.strictEqual(parseString('"foo"'), '"foo"') + assert.strictEqual(parseString('"2"'), '"2"') + assert.strictEqual(parseString('\'foo\''), '\'foo\'') }) it('should find a unique name', () => {