"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Safely Parse \"Relaxed\" JSON Without Using `eval`?

How Can I Safely Parse \"Relaxed\" JSON Without Using `eval`?

Published on 2024-11-07
Browse:834

How Can I Safely Parse \

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.

Latest tutorial More>

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