Created
July 11, 2023 18:53
-
-
Save jsbeaudry/a0c89d60b1acc35bdbb1c2c9b0af1fce to your computer and use it in GitHub Desktop.
How to get validated objects of a streaming text from chatGPT API
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
const extractObjects = (arrayString) => { | |
const objectPattern = /{[^{}]*}/g; | |
const objects = arrayString.match(objectPattern); | |
if (objects) { | |
const parsedObjects = objects.map((objString) => { | |
try { | |
return JSON.parse(objString); | |
} catch (error) { | |
console.error("Error parsing object:", error); | |
return null; | |
} | |
}); | |
const validObjects = parsedObjects.filter((obj) => obj !== null); | |
return validObjects; | |
} | |
return []; | |
}; | |
export default extractObjects; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment