You can do this by replacing the regex:
var json = "[ {Name: 'Jane', Id: '005b0000000MGa7AAG'}, {Name: 'Tom', Id: '005b0000000MGa7AAF'} ]"; var newJson = json.replace(/([a-zA-Z0-9]+?):/g, '"$1":'); newJson = newJson.replace(/'/g, '"'); var data = JSON.parse(newJson); alert(data[0]["Name"]);
First of all, we end the property names with quotes, then we replace single quotes with double quotes. This is enough to make it valid JSON, which can then be parsed.
Here is a working example
NOTE Using RegEx in general for such things is not ideal, and this solution will only work under certain circumstances (for example, in this example). As mentioned in the comments, one problem would be if the data values ββcontained a colon :
With this in mind, this is a more reliable solution:
var json = $("div").html(); var newJson = json.replace(/'/g, '"'); newJson = newJson.replace(/([^"]+)|("[^"]+")/g, function($0, $1, $2) { if ($1) { return $1.replace(/([a-zA-Z0-9]+?):/g, '"$1":'); } else { return $2; } }); var data = JSON.parse(newJson); alert(data[0]["Name"]);
This will match any variables (alphanumeric) ending with a colon : but will contain any matches found between quotation marks (i.e. data string values)
Here is an example
musefan
source share