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!
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 ".
Also, you probably want to use booleans true/false instead of strings "true"/"false".
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>');
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With