use javascript inbuild functions escape and unescape
for example
var escapedData = escape("hel'lo");
output = "%27hel%27lo%27" which can be used in the attribute.
again to read the value from the attr
var unescapedData = unescape("%27hel%27lo%27")
output = "'hel'lo'"
This will be helpful if you have huge json stringify data to be used in the attribute