Home > Web Front-end > JS Tutorial > body text

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

Mary-Kate Olsen
Release: 2024-10-30 14:08:56
Original
727 people have browsed it

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:

<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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!