Skip to content

Instantly share code, notes, and snippets.

@franzwong
Last active January 27, 2020 07:22
Show Gist options
  • Save franzwong/635037cf78bf6ac40228f6b07592ab7e to your computer and use it in GitHub Desktop.
Save franzwong/635037cf78bf6ac40228f6b07592ab7e to your computer and use it in GitHub Desktop.
Extract json from plain text
/**
* Example
* Input: 'INFO Records: {"user": {"name": "luke", "type": "jedi"}}{"name": "leia"}, Record count: 2'
* Output: [
"INFO Records: ",
"{\n \"user\": {\n \"name\": \"luke\",\n \"type\": \"jedi\"\n }\n}",
"{\n \"name\": \"leia\"\n}",
", Record count: 2"
]
*/
function extractJson(message) {
const lines = [];
let offset = 0;
let last = 0;
while (true) {
let startIndex = message.indexOf('{', offset);
if (startIndex < 0) {
if (last < message.length) {
lines.push(message.substring(last));
}
break;
}
let endIndex = startIndex;
while (endIndex >= 0) {
endIndex = message.indexOf('}', endIndex + 1);
if (endIndex < 0) {
break;
}
try {
const fragment = message.substring(startIndex, endIndex + 1);
const json = JSON.parse(fragment);
if (last !== startIndex) {
lines.push(message.substring(last, startIndex));
}
lines.push(JSON.stringify(json, null, 2));
offset = last = endIndex + 1;
break;
} catch (err) {
}
}
if (endIndex < 0) {
offset++;
}
}
return lines;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment