Skip to content

Instantly share code, notes, and snippets.

@jsbeaudry
Created July 11, 2023 18:53
Show Gist options
  • Save jsbeaudry/a0c89d60b1acc35bdbb1c2c9b0af1fce to your computer and use it in GitHub Desktop.
Save jsbeaudry/a0c89d60b1acc35bdbb1c2c9b0af1fce to your computer and use it in GitHub Desktop.
How to get validated objects of a streaming text from chatGPT API
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