Parsing JSON data that follows a "relaxed" syntax with unquoted keys presents a challenge, especially when aiming to avoid the potentially hazardous use of eval.
One solution is to employ a regular expression replacement to sanitize the JSON string. By replacing unquoted key-value pairs with their quoted equivalents, we can create a JSON string that adheres to the standard syntax.
Consider the following example:
var badJson = "{muh: 2}"; // Sanitize the JSON using regular expression var correctJson = badJson.replace(/(['"])?([a-z0-9A-Z_]+)(['"])?:/g, '"": '); // Now we can safely parse the corrected JSON JSON.parse(correctJson);
This approach allows us to parse "relaxed" JSON data without compromising security or triggering JSHint warnings, providing a convenient and safe alternative to eval for your testing purposes.
The above is the detailed content of How Can I Parse \'Relaxed\' JSON Without Using `eval`?. For more information, please follow other related articles on the PHP Chinese website!