I'm having difficulty in parsing JSON data to JavaScript. I wanted to be able to customize the CSS feature by just using JSON. As an example, I wanted to build just a basic button. I created CSS style and linked it into HTML. However, I do not know such a way to make sure when Javascript read the JSON data, it will provide a right answer. As CSS involves with numerical value (etc width:50%), it makes me harder to customize.
I wanted to change the size of button, background-color, padding as well as the text in the button.
Can anyone help me on this. Thank you I used this code to parse Json into html
var info=JSON.parse(request.responseText);
------JSON file------
{
"button": {
"width" : "100%",
"backgroundColor": "#4CAF50",
"border": "none",
"color": "red",
"padding": "15px 32px",
"textAlign": "center",
"textDecoration": "none",
"display": "inline-block",
"fontSize": "16px",
"margin": "4px 2px",
"cursor": "pointer"
}
}
JS file
window.onload = loadJSON;
function loadJSON()
{
var request;
if (window.XMLHttpRequest){
request=new XMLHttpRequest();
} else {
request =new ActiveXObject("Microsoft.XMLHTTP");
}
request.onreadystatechange = function()
{
if ((request.status ===200) &&
(request.readyState ===4))
{
var info=JSON.parse(request.responseText);
if(info!= null)
{
Object.keys(info).forEach(function(k) {
$('<' + k + ' />', info[k].attr).css(info[k].css).appendTo('#container');
});
}
else {alert("error")};
}
}
Here is the latest code. I would like to know is it possible if I wanted to customize more than one buttons? what should be the code as I can't solve it.