Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape JSON in an HTML string stored as a Javascript variable?

I'm trying to parse a JSON string and I can't get it to work because of illegal chracters - which I cannot find...

Here is what I have:

make = function (el) {
    var config = el.getAttribute("data-config");
    console.log(config);
    var dyn = $.parseJSON(config)
    console.log(dyn);
}

var a= document.createElement("<a href='#' class='template' data-config=\"{'role':'button','iconpos':'left','icon':'star','corners':'false','shadow':'false', 'iconshadow':'false', 'theme':'a','class':'test', 'href':'index.html','text':'Star Icon', 'mini':'true', 'inline':'true'}\">Star Icon</a>");
console.log(a);
make(a);

I'm not really sure how to correctly unescape the JSON in my original string "a", so that it works.

Question_:
Which quotation marks do I need to escape to get this to work?

Thanks!

EDIT:

Ok. I figured it out using Jquery (I'd prefer Javascript-only though). This works:

make = function (el) {
    var config = el.attr("data-config");
        console.log(config);
    var dyn = $.parseJSON(config)
        console.log(dyn);
}

var c = $('<a href="#" class="template" data-config=\'{"role":"button","iconpos":"left","icon":"star","corners":"false","shadow":"false", "iconshadow":"false", "theme":"a","class":"test", "href":"index.html","text":"Star Icon", "mini":"true", "inline":"true"}\'>Star Icon</a>')
console.log(c);
make(c);

So escaping the start/end quotations of the JSON string seems to do the trick. The actual problem was that I can not use document.createElement with a full string. I can only create the element document.createElement(a) and then set innerHTML. Need to look into this some more.

If someone can tell me a Javascript-only way how to do this, please let me know.

Thanks!

like image 615
frequent Avatar asked Jul 07 '26 22:07

frequent


1 Answers

Strings and object keys in JSON must be double quoted. Double quotes in attributes are not valid, so you'll need to escape them with &quot;.

Also, you probably want to use booleans true/false instead of strings "true"/"false".

var a = document.createElement('<a href="#" class="template" data-config="{&quot;role&quot;:&quot;button&quot;,&quot;iconpos&quot;:&quot;left&quot;,&quot;icon&quot;:&quot;star&quot;,&quot;corners&quot;:false,&quot;shadow&quot;:false,&quot;iconshadow&quot;:false,&quot;theme&quot;:&quot;a&quot;,&quot;class&quot;:&quot;test&quot;, &quot;href&quot;:&quot;index.html&quot;,&quot;text&quot;:&quot;Star Icon&quot;, &quot;mini&quot;:true,&quot;inline&quot;:true}\">Star Icon</a>');

Notice this is completely unreadable and @millimoose's suggestion about just setting the attribute afterwards will make this much easier to deal with in the long run.

like image 159
Matt Ball Avatar answered Jul 10 '26 10:07

Matt Ball



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!