An algorithm for separating embedded JSON from a string, nicely packaged into a node.js module.
npm install json-from-textjavascript
Object jsonFromText(String mixedStr, Boolean parseToObject)
`
$3
* mixedStr: The string to separate the JSON from the text.
* parseToObject: If set to false, the resulting JSON strings will not be translated to JSON objects. Default is true.
Example
$3
`javascript
var jsonFromText = require('json-from-text');
var sampleText = "There was a change from {'animal':'dog', 'color':'blue'} to {'animal':'cat', 'color':'red'}'";
var results = jsonFromText(sampleText);
console.log(JSON.stringify(results, null, 2));
`
$3
`json
{
"textResults": [
"There was a change from '",
"' to '",
"'"
],
"jsonResults": [
{
"animal": "dog",
"color": "blue"
},
{
"animal": "cat",
"color": "red"
}
],
"fullResults": [
{
"type": "text",
"value": "There was a change from '"
},
{
"type": "json",
"parsed": true,
"value": {
"animal": "dog",
"color": "blue"
}
},
{
"type": "text",
"value": "' to '"
},
{
"type": "json",
"parsed": true,
"value": {
"animal": "cat",
"color": "red"
}
},
{
"type": "text",
"value": "'"
}
]
}
``