Skip to content

Instantly share code, notes, and snippets.

@elitan
Created November 5, 2023 10:13
Show Gist options
  • Save elitan/201a2d8497e4a8fcd1e51ed7f5d49971 to your computer and use it in GitHub Desktop.
Save elitan/201a2d8497e4a8fcd1e51ed7f5d49971 to your computer and use it in GitHub Desktop.
Parse Open AI function calls JSON response with JavaScript/TypeScript
function escapeNewLines(str: string) {
return str.replace(/\n/g, '\\n');
}
function fixOpenAiNewLineResponse(str: string) {
return str
.split('"')
.map((chunk, index) => {
// Only replace \n inside the JSON string values, which are in every other index after splitting by "
if (index % 2 === 1) {
return escapeNewLines(chunk);
} else {
return chunk;
}
})
.join('"');
}
export function parseOpenAiJson(str: string) {
return JSON.parse(fixOpenAiNewLineResponse(str));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment