Home >Web Front-end >JS Tutorial >Why Does jQuery.parseJSON Throw \'Invalid JSON\' Error When Escaped Single Quotes Are Present?
jQuery.parseJSON Throws "Invalid JSON" Error Due to Escaped Single Quote in JSON
Problem:
When using jQuery.post() to retrieve JSON objects from a server, parsing fails if any of the values contain an escaped single quote ('). This occurs even though the JSON string is otherwise valid.
Reason:
According to the JSON specification, only escaped double-quotes are allowed within strings, not single-quotes. Single-quote characters do not need to be escaped according to the JSON standard.
Update:
During a discussion about JSON in "JavaScript: The Good Parts," Douglas Crockford, the creator of JSON, explained that the decision to only allow escaped double-quotes was made to simplify interoperability. By requiring the use of double-quotes only, it eliminates the potential for confusion and accidental termination of strings.
Implications:
This means that it is impossible for a single quote character within a JSON string to inadvertently terminate the string. Hence, escaping single quote characters is not necessary in the formal JSON specification.
Implementation Considerations:
While the JSON specification does not allow escaped single quotes, bazı implementations, such as org.json for Java, are more lenient and permit their use. However, it is essential to note that this is not the norm, and many popular implementations, including the one used by jQuery, strictly adhere to the official JSON specification and reject JSON containing single quoted strings and/or escaped single quotes.
jQuery.parseJSON Behavior:
jQuery.parseJSON relies on the underlying JSON parser provided by the browser or a loaded library like json2.js. Since these implementations are typically compliant with the JSON specification, they do not allow escaped single quotes, and thus neither does jQuery.
The above is the detailed content of Why Does jQuery.parseJSON Throw \'Invalid JSON\' Error When Escaped Single Quotes Are Present?. For more information, please follow other related articles on the PHP Chinese website!