Reputation: 28545
It seems that by default javascript appends attributes using double quotes. However in my situation I am attempting to append a json string to a data attribute and the double quote interferes with the json.
var json = {"foo":"bar"}
var el = document.getElementById("someElement");
el.setAttribute("data-json", JSON.stringify(json)); //<div data-json="{"foo":"bar"}">
How can I append an attribute using a single quote?
Upvotes: 6
Views: 2505
Reputation:
It is incorrect to say that
by default javascript appends attributes using double quotes.
An attribute is merely a string. The attribute value itself does not include the surrounding quotes. Quotes are nothing more than syntax for representing a string literal. The outside quotes you see surrounding the attribute in
<div data-json="{"foo":"bar"}">
do not exist in the attribute value; they were simply inserted by the console when it is printing out the attribute for your visual convenience. There is nothing "interfering with the JSON". The attribute value can be retrieved and parsed with JSON.parse
as is with no further ado.
var json = {"foo":"bar"}
var el = document.getElementById("someElement");
el.setAttribute("data-json", JSON.stringify(json));
// now, parse the attribute
>> JSON.parse(el.getAttribute('data-json'))
<< Object {foo: "bar"}
Upvotes: 6
Reputation: 17541
I think the better practice is string escaping (see adeneo's answer).
But just as an other option you may be able to replace double quotes with single quotes by .replace()
function:
var json = {"foo":"bar"}
var encoded = JSON.stringify(json);
encoded = encoded.replace(/\\"/g, '"')
.replace(/([\{|:|,])(?:[\s]*)(")/g, "$1'")
.replace(/(?:[\s]*)(?:")([\}|,|:])/g, "'$1")
.replace(/([^\{|:|,])(?:')([^\}|,|:])/g, "$1\\'$2");
var el = document.getElementById("someElement");
el.setAttribute("data-json", encoded);
Attention the result string "{'foo':'bar'}"
is not a valid json
Upvotes: 0