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!