Last active
December 4, 2023 15:52
-
-
Save justin-schroeder/f7d0d9191eb89b0ea0bcc5b2b73d8177 to your computer and use it in GitHub Desktop.
JSON Completer (closeJSON)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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