[SalesForce] How to successfully escape single quotes in a string that will be accessed in Javscript? (Apex)

I am trying to account for if a single quote makes it into a field name, or a value of a picklist/multi-picklist, but can't seem to figure out a way to handle it.

I go through and get all the fields in a field set, then serialize them into JSON, and then I grab that JSON string in my Javascript on the client side, then parse the fields out with JSON.parse(). Obviously, a single quote will break this…

I have tried to use escapeSingleQuotes, but my JSON string on my client side has \ where the single quotes used to be instead of \'. I don't know how the single quote disappeared… If this would work as expected, I believe my issue would be resolved, but just having \ instead of \' breaks the JSON.parse as well.

The single quote would need to just be escaped, since if it is a value of a picklist/multi-picklist, it cannot be replaced with something else or it can't be selected and saved because that value won't exist in the picklist/multi-picklist.

Best Answer

I go through and get all the fields in a field set, then serialize them into JSON, and then I grab that JSON string in my Javascript on the client side, then parse the fields out with JSON.parse(). Obviously, a single quote will break this...

If you are passing the JSON properly to your JS, it should not matter what the field values are. Apex produces standards-compliant JSON (unless someone has an egregious counterexample?) and JavaScript reads it the same way.