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

How to Safely Parse Relaxed JSON Without Using `eval`?

Mary-Kate Olsen
Release: 2024-10-31 05:44:02
Original
583 people have browsed it

How to Safely Parse Relaxed JSON Without Using `eval`?

Parsing Relaxed JSON Safely

Parsing "relaxed" JSON without resorting to the potentially dangerous eval function is a common challenge when working with JSON data that may not adhere to strict JSON syntax. While JSON.parse() requires keys to be quoted, some scenarios require parsing JSON with unquoted keys for convenience or legacy reasons.

One approach to handle "relaxed" JSON safely is to sanitize the JSON before parsing it. Using a regular expression replace, you can convert unquoted keys into quoted ones while preserving the rest of the JSON structure.

var badJson = "{muh: 2}";
var correctJson = badJson.replace(/(['"])?([a-z0-9A-Z_]+)(['"])?:/g, '"": ');
Copy after login

In this example, the regular expression searches for unquoted keys surrounded by optional single or double quotes, followed by a colon. It then replaces the matches with the correct quoted key syntax, ensuring that the JSON string now meets the proper JSON format.

Once the JSON string is sanitized, you can safely parse it using JSON.parse():

JSON.parse(correctJson);
Copy after login

This method allows you to parse "relaxed" JSON with unquoted keys while maintaining the security and reliability of JSON parsing without the need for custom parsers or unsafe techniques like eval.

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