Home >Web Front-end >JS Tutorial >How to Parse JSON Strings Containing Single Quotes?

How to Parse JSON Strings Containing Single Quotes?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-15 00:43:11242browse

How to Parse JSON Strings Containing Single Quotes?

Parsing JSON with Single Quotes

When attempting to parse a JSON string with single quotes, such as str = "{'a':1};", you may encounter a SyntaxError. This error occurs because JSON follows a strict syntax that requires the use of double quotes for keys and values.

Solution:

To successfully parse the string into a JSON object, you should replace the single quotes with double quotes. Here's an example:

const str = "{'a':1}";
const replacedStr = str.replace(/'/g, '"');
const json = JSON.parse(replacedStr);

In this example, we use the replace() method to replace all occurrences of single quotes with double quotes, creating a valid JSON string. We then parse the modified string using JSON.parse() to obtain the corresponding JSON object. This approach ensures adherence to the JSON syntax while preserving the data within the string.

The above is the detailed content of How to Parse JSON Strings Containing Single Quotes?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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