Parsing "Relaxed" JSON Without Risky Evaluation
JSON, a widely used data exchange format, requires strict syntax with quoted keys. However, certain applications may encounter "relaxed" JSON with unquoted keys. Parsing such data using eval is discouraged due to security risks.
Avoiding Evil Eval
One alternative to eval is a regular expression-based approach that sanitizes the JSON before parsing. This method scans the JSON string and replaces any unquoted keys with quoted ones, ensuring compliance with standard JSON syntax without compromising security.
Example Implementation
To implement this approach, follow these steps:
<code class="javascript">var badJson = "{muh: 2}"; // Sanitize the JSON using regular expression replace var correctJson = badJson.replace(/(['"])?([a-z0-9A-Z_]+)(['"])?:/g, '"": '); // Parse the sanitized JSON using JSON.parse var obj = JSON.parse(correctJson);</code>
Conclusion
Using regular expressions to sanitize relaxed JSON allows for seamless parsing while avoiding the potential security risks associated with eval.
The above is the detailed content of How Can I Safely Parse \'Relaxed\' JSON Without Using `eval`?. For more information, please follow other related articles on the PHP Chinese website!