Problem Statement

You are given a JSON object that represents an HTML structure.
Your task is to implement a function JSONtoHTML(json) that converts this JSON structure into a real HTML element (DOM node).

Each node in the JSON can contain:

  • type: The HTML tag (like "div", "p", "span")
  • props: An object of HTML attributes (like { id: "main", class: "title" })
  • children: Either a string (text content) or an array of nested child elements

You must recursively build the corresponding HTML structure.


Example

Input:

const json = {
type: "div",
props: { id: "hello", class: "foo" },
children: [
{ type: "h1", children: "HELLO" },
{
type: "p",
children: [{ type: "span", props: { class: "bar" }, children: "World" }],
},
],
};

Output (HTML):

<div id="hello" class="foo">
<h1>HELLO</h1>
<p>
<span class="bar">World</span>
</p>
</div>

Constraints

  • You cannot use external libraries like React or JSDOM.
  • You must build and return the DOM structure recursively.
  • Throw an error if the JSON format is invalid (missing type or not an object).

Example Run

const json = {
type: "div",
props: { id: "hello", class: "foo" },
children: [
{ type: "h1", children: "HELLO" },
{
type: "p",
children: [{ type: "span", props: { class: "bar" }, children: "World" }],
},
],
};

console.log(JSONtoHTML(json));

Expected Output

<div id="hello" class="foo">
<h1>HELLO</h1>
<p>
<span class="bar">World</span>
</p>
</div>