Home > Web Front-end > JS Tutorial > How Can I Parse \'Relaxed\' JSON Without Using `eval`?

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

Susan Sarandon
Release: 2024-11-03 21:11:02
Original
411 people have browsed it

How Can I Parse

Parsing "Relaxed" JSON Without Resorting to eval

Parsing JSON data that follows a "relaxed" syntax with unquoted keys presents a challenge, especially when aiming to avoid the potentially hazardous use of eval.

One solution is to employ a regular expression replacement to sanitize the JSON string. By replacing unquoted key-value pairs with their quoted equivalents, we can create a JSON string that adheres to the standard syntax.

Consider the following example:

var badJson = "{muh: 2}";

// Sanitize the JSON using regular expression
var correctJson = badJson.replace(/(['"])?([a-z0-9A-Z_]+)(['"])?:/g, '"": ');

// Now we can safely parse the corrected JSON
JSON.parse(correctJson);
Copy after login

This approach allows us to parse "relaxed" JSON data without compromising security or triggering JSHint warnings, providing a convenient and safe alternative to eval for your testing purposes.

The above is the detailed content of How Can I 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