I have an ASP.NET MVC 4 application where a list of classes, with their full namespaces, are bound to a listbox. This generates HTML as follows:
<select id="myclasses">
<option>Api.Domain.Interfaces.MyClass1</option>
<option>Api.Domain.Interfaces.MyClass2</option>
<option>Api.Domain.Interfaces.MyClass3</option>
<option>Api.Domain.Models.MyModel1</option>
<option>Api.Domain.Models.MyModel2</option>
<option>Api.Infrastructure.Repositories.MyRepo1</option>
<option>Api.Infrastructure.Repositories.MyRepo2</option>
</select>
I would like to use JavaScript/jQuery to generate a JSON representation of this HTML stored in a variable as follows:
var classes =
[{ "text": "Api", "children":
[{ "text": "Domain", "children":
[{ "text": "Interfaces", "children":
[{ "text": "MyClass1" }, { "text": "MyClass2" }, { "text": "MyClass3" }]
},
{ "text": "Models", "children":
[{ "text": "MyModel1" }, { "text": "MyModel2" }]
}]
},
{ "text": "Infrastructure", "children":
[{ "text": "Repositories", "children":
[{ "text": "MyRepo1" }, { "text": "MyRepo2" }]
}]
}]
}];
The fully qualified class names are already in a tree-like structure, so I would imagine that there should be a fairly easy way to achieve what I'm trying to do. Should I be getting the inner HTML of the element using $("#myclasses").html()
and then performing string manipulations, or is there a simpler way?