devuser devuser - 4 months ago 19
Javascript Question

Json to html ul list. Pure javascript

How to convert json response into html ul list?

{
"subject": [
"The subject field is required."
],
"message": [
"The message field is required."
]
}


to this

<ul>
<li>The subject field is required</li>
<li>The message field is required</li>
</ul>


And show it in some div

<div id="errors"></div>

Answer

Try this:

var parent = document.createElement("ul");
document.body.appendChild(parent);

var obj = {
    "subject": [
        "The subject field is required."
    ],
    "message": [
        "The message field is required."
    ]
}

var keys = Object.keys(obj);

for(var i = 0; i < keys.length; i++) {
  var child = document.createElement("li");
  child.innerHTML = obj[keys[i]][0];
  parent.appendChild(child);
}