Somewhat more resilient way, in case of nested data, would be to try to use RegEx to find the beginning of the JSON and then match opening/closing braces until you find the end of it.
Something like this:
string ExtractJson(string source)
{
var buffer = new StringBuilder();
var depth = 0;
// We trust that the source contains valid json, we just need to extract it.
// To do it, we will be matching curly braces until we even out.
for (var i = 0; i < source.Length; i++)
{
var ch = source[i];
var chPrv = i > 0 ? source[i - 1] : default;
buffer.Append(ch);
// Match braces
if (ch == '{' && chPrv != '\\')
depth++;
else if (ch == '}' && chPrv != '\\')
depth--;
// Break when evened out
if (depth == 0)
break;
}
return buffer.ToString();
}
// ...
var input = "...";
var json = ExtractJson(Regex.Match(input, @"data=\{(.*)\}").Groups[1].Value);
var jsonParsed = JToken.Parse(json);
This handles situations where there might be multiple json blobs in the input, or some other content that also contains braces.
JSON.Net- james.newtonking.com/projects/json-net.aspx