An AJAX call is returning a response text that includes a JSON string. I need to:
- extract the JSON string
- modify it
- then reinsert it to update the original string
I am not too worried about steps 2 and 3, but I can’t figure out how to do step 1. I was thinking about using a regular expression, but I don’t know how as my JSON might have multiple levels with nested objects or arrays.
You cannot use a regex to extract JSON from an arbitrary text. Since regexes are usually not powerful enough to validate JSON (unless you can use PCRE) they also cannot match it – if they could, they could also validate JSON.
However, if you know that the top-level element of your JSON is always an object or array, you can go by the following approach:
{or[) and last closing (}or]) brace in your string.JSON.parse(). If it succeeded, finish and return the parsed result.Here is a function that extracts a JSON object and returns the object and its position. If you really need top-level arrays, too, it should be to extend:
Demo (executed in the nodejs environment, but should work in a browser, too): https://paste.aeum.net/show/81/