Parsing Relaxed JSON Safely
Parsing "relaxed" JSON without resorting to the potentially dangerous eval function is a common challenge when working with JSON data that may not adhere to strict JSON syntax. While JSON.parse() requires keys to be quoted, some scenarios require parsing JSON with unquoted keys for convenience or legacy reasons.
One approach to handle "relaxed" JSON safely is to sanitize the JSON before parsing it. Using a regular expression replace, you can convert unquoted keys into quoted ones while preserving the rest of the JSON structure.
var badJson = "{muh: 2}"; var correctJson = badJson.replace(/(['"])?([a-z0-9A-Z_]+)(['"])?:/g, '"": ');
In this example, the regular expression searches for unquoted keys surrounded by optional single or double quotes, followed by a colon. It then replaces the matches with the correct quoted key syntax, ensuring that the JSON string now meets the proper JSON format.
Once the JSON string is sanitized, you can safely parse it using JSON.parse():
JSON.parse(correctJson);
This method allows you to parse "relaxed" JSON with unquoted keys while maintaining the security and reliability of JSON parsing without the need for custom parsers or unsafe techniques like eval.
The above is the detailed content of How to Safely Parse Relaxed JSON Without Using `eval`?. For more information, please follow other related articles on the PHP Chinese website!