Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON string containing escaped single quote flagged as invalid

JSONLint says the following is invalid JSON:

[{
"value": 71,
"label": "123 Foobar \'eha-Kauai, Hawaii, United States"
},
{
"value": 75,
"label": "456 Foobar \'elima-Kauai, Hawaii, United States"
}]

Yet this works:

var foo = [{
"value": 71,
"label": "123 Foobar \'eha-Kauai, Hawaii, United States"
},
{
"value": 75,
"label": "456 Foobar \'elima-Kauai, Hawaii, United States"
}];
console.log(foo.length); // returns 2

Note: the string is generated by a function which could be used in the following ways:

<script>
var foo = '<%= vbs_JSONEncode("Hello World") %>'; // being inconsistent
var bar = "<%= vbs_JSONEncode(str_Hello_Msg) %>"; // with the quotes
</script>

Or simply:

Response.ContentType = "application/json"
Response.Write vbs_JSONEncode("Hello World")
like image 978
Salman A Avatar asked Mar 21 '26 16:03

Salman A


2 Answers

You don't need to escape a ' with a backslash. Just escape the ".

like image 96
dogbane Avatar answered Mar 23 '26 04:03

dogbane


The issue is the escaping of the single-quote marks, which is unnecessary in JSON, since only double quotes are used.

like image 41
nickf Avatar answered Mar 23 '26 04:03

nickf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!