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:
var badJson = "{muh: 2}";
// Sanitize the JSON using regular expression replace
var correctJson = badJson.replace(/(['"])?([a-z0-9A-Z_] )(['"])?:/g, '"$2": ');
// Parse the sanitized JSON using JSON.parse
var obj = JSON.parse(correctJson);
Conclusion
Using regular expressions to sanitize relaxed JSON allows for seamless parsing while avoiding the potential security risks associated with eval.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3