Skip to content

Instantly share code, notes, and snippets.

@justin-schroeder
Last active December 4, 2023 15:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save justin-schroeder/f7d0d9191eb89b0ea0bcc5b2b73d8177 to your computer and use it in GitHub Desktop.
Save justin-schroeder/f7d0d9191eb89b0ea0bcc5b2b73d8177 to your computer and use it in GitHub Desktop.
JSON Completer (closeJSON)
/**
* Given an incomplete JSON string, return the string with the missing
* closing characters.
* @param str - An incomplete json string
*/
export function closeJSON(incompleteJson: string) {
let char = ''
let lastChar = ''
let chars = [...incompleteJson]
let isQuoted = false
let depthMap: Array<'{' | '['> = []
for (let i = 0; i < chars.length; i++) {
lastChar = char
char = chars[i]
if (isQuoted && char === '"' && lastChar !== '\\') {
isQuoted = false
} else if (!isQuoted) {
switch (char) {
case '"':
if (lastChar !== '\\') {
isQuoted = true
}
break
case '{':
case '[':
depthMap.push(char)
break
case '}':
case ']':
depthMap.pop()
break
}
}
}
if (isQuoted) {
incompleteJson += '"'
}
while (depthMap.length > 0) {
const toClose = depthMap.pop()
if (toClose === '{') incompleteJson += '}'
if (toClose === '[') incompleteJson += ']'
}
return incompleteJson
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment