Fix #794: fix discrepancy between valid JSON numbers and valid JavaScript numbers

This commit is contained in:
jos 2019-09-15 11:55:15 +02:00
parent 97cda1457a
commit 8554789aa7
3 changed files with 38 additions and 14 deletions

View File

@ -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.

View File

@ -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
}
/**

View File

@ -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', () => {