Skip to content

Commit

Permalink
A fix in repairing line-separated json
Browse files Browse the repository at this point in the history
  • Loading branch information
josdejong committed Mar 25, 2020
1 parent fd0db5d commit 4f433cb
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
12 changes: 11 additions & 1 deletion src/js/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,16 @@ export function repair (jsString) {
return jsString[iNext]
}

// get at the first non-white space character starting at the current character
function currNonWhiteSpace () {
let iNext = i
while (iNext < jsString.length && isWhiteSpace(jsString[iNext])) {
iNext++
}

return jsString[iNext]
}

// skip a block comment '/* ... */'
function skipBlockComment () {
if (curr() === '/' && next() === '*') {
Expand Down Expand Up @@ -299,7 +309,7 @@ export function repair (jsString) {
const whitespaces = parseWhiteSpace()
skipBlockComment()

if (curr() === '{' || nextNonWhiteSpace() === '{') {
if (currNonWhiteSpace() === '{') {
chars.push(',')
if (indent === 0) {
isLineSeparatedJson = true
Expand Down
8 changes: 7 additions & 1 deletion test/util.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ describe('util', () => {
assert.strictEqual(repair('callback({}'), 'callback({}')
})

it('should strip trailing zeros', () => {
it('should strip trailing commas', () => {
// matching
assert.strictEqual(repair('[1,2,3,]'), '[1,2,3]')
assert.strictEqual(repair('[1,2,3,\n]'), '[1,2,3\n]')
Expand Down Expand Up @@ -161,6 +161,12 @@ describe('util', () => {
assert.strictEqual(repair(text), expected)
})

it('should not repair normal array with comma separated objects', () => {
const text = '[\n{},\n{}\n]'

assert.strictEqual(repair(text), text)
})

it('should repair line separated json (for example from robo3t', () => {
const text = '' +
'/* 1 */\n' +
Expand Down

0 comments on commit 4f433cb

Please sign in to comment.