Skip to content

Instantly share code, notes, and snippets.

@laocoi
Last active March 30, 2025 09:28
Show Gist options
  • Save laocoi/d9524333ebe8247e587a972daad73e9e to your computer and use it in GitHub Desktop.
Save laocoi/d9524333ebe8247e587a972daad73e9e to your computer and use it in GitHub Desktop.
Parse JSON object from GPT response
function gpt_json_parse(gptResponse){
try {
if(/^```json(.*)```/s.test(gptResponse)){
let m = gptResponse.match(/```json(.*)```/s)
gptResponse = m[1]
}
return JSON.parse(gptResponse.replaceAll('\n',''))
}catch(e){
console.log("Something went wrong, cannot parse JSON object")
return gptResponse
}
}
let gptResponse = '```json\n' +
'{\n' +
' "title": "Cute Cartoon Character in Purple Costume",\n' +
` "description": "A playful and whimsical illustration of a cute cartoon character wearing a purple costume with an adorable pig face. The character is striking a confident pose on a soft pink background, perfect for children's products, digital content, and playful designs.",\n` +
' "keywords": [\n' +
' "cute character",\n' +
' "cartoon",\n' +
' "purple costume",\n' +
' "pig design",\n' +
' "kawaii",\n' +
' "whimsical illustration",\n' +
` "children's art",\n` +
' "playful",\n' +
' "vector art",\n' +
' "anime style",\n' +
' "adorable",\n' +
' "fantasy character",\n' +
' "colorful",\n' +
' "fun",\n' +
' "anime"\n' +
' ]\n' +
'}\n' +
'```'
console.log(gpt_json_parse(gptResponse))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment