Skip to content

Commit

Permalink
Implement support for inserting missing end brackets
Browse files Browse the repository at this point in the history
  • Loading branch information
josdejong committed Nov 5, 2020
1 parent 803608a commit af41cda
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 7 deletions.
2 changes: 1 addition & 1 deletion docs/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ <h1>simple-json-repair</h1>
<textarea id="input-text" autocomplete="off" autocapitalize="off" spellcheck="false">{
'firstName': 'John'

lastName: “Smith”
lastName “Smith”

fullName: John Smith,

Expand Down
15 changes: 15 additions & 0 deletions src/simpleJsonRepair.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,21 @@ describe('jsonRepair2', () => {
strictEqual(simpleJsonRepair('"{a:2,}"'), '"{a:2,}"')
})

it('should add a missing closing bracket for an object', () => {
strictEqual(simpleJsonRepair('{"a":2'), '{"a":2}')
strictEqual(simpleJsonRepair('{"a":{"b":2}'), '{"a":{"b":2}}')
strictEqual(simpleJsonRepair('{\n "a":{"b":2\n}'), '{\n "a":{"b":2\n}}')
strictEqual(simpleJsonRepair('[{"b":2]'), '[{"b":2}]')
strictEqual(simpleJsonRepair('[{"b":2\n]'), '[{"b":2}\n]')
strictEqual(simpleJsonRepair('[{"i":1{"i":2}]'), '[{"i":1},{"i":2}]')
// TODO strictEqual(simpleJsonRepair('[{"i":1,{"i":2}]'), '[{"i":1},{"i":2}]')
})

it('should add a missing closing bracket for an array', () => {
strictEqual(simpleJsonRepair('[1,2,3'), '[1,2,3]')
strictEqual(simpleJsonRepair('{\n"values":[1,2,3\n}'), '{\n"values":[1,2,3]\n}')
})

it('should strip MongoDB data types', () => {
// simple
strictEqual(simpleJsonRepair('{"_id":ObjectId("123")}'), '{"_id":"123"}')
Expand Down
16 changes: 10 additions & 6 deletions src/simpleJsonRepair.ts
Original file line number Diff line number Diff line change
Expand Up @@ -490,10 +490,12 @@ function parseObject () {
}

// @ts-ignore
if (tokenType !== DELIMITER || token !== '}') {
throw new JsonRepairError('Comma or end of object "}" expected', index - token.length)
if (tokenType === DELIMITER && token === '}') {
processNextToken()
} else {
// missing end bracket -> insert the missing bracket
output = insertBeforeLastWhitespace(output, '}')
}
processNextToken()

return
}
Expand Down Expand Up @@ -543,10 +545,12 @@ function parseArray () : void {
}

// @ts-ignore
if (tokenType !== DELIMITER || token !== ']') {
throw new JsonRepairError('Comma or end of array "]" expected', index - token.length)
if (tokenType === DELIMITER && token === ']') {
processNextToken()
} else {
// missing end bracket -> insert the missing bracket
output = insertBeforeLastWhitespace(output, ']')
}
processNextToken()
return
}

Expand Down

0 comments on commit af41cda

Please sign in to comment.