Home >Web Front-end >JS Tutorial >How to Parse a JSON String with Single Quotes Instead of Double Quotes?

How to Parse a JSON String with Single Quotes Instead of Double Quotes?

Susan Sarandon
Susan SarandonOriginal
2024-12-01 00:55:12136browse

How to Parse a JSON String with Single Quotes Instead of Double Quotes?

Parsing String as JSON with Single Quotes?

When attempting to parse a string as JSON, you may encounter issues if the string contains single quotes instead of the required double quotes.

Problem Statement:

Consider the example string str = {'a':1}, where single quotes are used around the object key. Parsing this string using JSON.parse(str) will result in the Uncaught SyntaxError: Unexpected token '…' exception.

Solution:

The JSON standard dictates that strings must be enclosed in double quotes. Parsing a string with single quotes will not be successful. To resolve this issue, there are two possible approaches:

  • Replace Single Quotes with Double Quotes: If the structure of the JSON is well-defined and does not contain escaped single quotes within strings (which is typically not valid for JSON), you can use the replace method to replace all single quotes with double quotes:
JSON.parse(str.replace(/'/g, '"'));
  • Parse Manually: If the JSON is complex and may contain escaped single quotes within strings, manual parsing is recommended. You can loop through the string, identify the various tokens (e.g., keys, values, commas, braces), and construct the JSON object incrementally.

The above is the detailed content of How to Parse a JSON String with Single Quotes Instead of Double 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