Created
November 5, 2023 10:13
-
-
Save elitan/201a2d8497e4a8fcd1e51ed7f5d49971 to your computer and use it in GitHub Desktop.
Parse Open AI function calls JSON response with JavaScript/TypeScript
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
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