I’ve encountered a situation where I need to replicate some JSON so that an area of the website can be content-managed. I have a json file I need to replicate. The taxonomy of the site is complex and unfortunately I am not in a position to change this.
I have set up the template in Umbraco and the data that I want is displaying on a page, but I do not know how to convert this to output as JSON.
Razor looks like this:
@{
dynamic memberships = Library.NodeById(1081);
var packageGroups = memberships.Descendants("Price");
foreach(var package in packageGroups) {
var top = package.AncestorOrSelf("Type");
var Description = (@top.HasValue("Blurb")) ? @top.Blurb : @top.Description;
var Locations = "";
foreach(var item in package.UserLocation.ToString().Split(',')) {
Locations += @Model.NodeById((@item)).Name;
Locations += ",";
}
<ul>
<li>Maintitle: @top.Parent().Title</li>
<li>Title: @top.Title</li>
<li>SubTitle: @SubTitle</li>
<li>Description: @Description</li>
<li>Link: @top.Url</li>
<li>Location: @Locations</li>
<li>Render: true</li>
</ul>
}
}
I need to output this to replicate the JSON file as below:
{
"items":[
{
"MainTitle":"Package Top Level Title",
"Title":"Package Title",
"SubTitle":"Additional Details",
"Description":"We wil provide you with some great products and services.",
"Link":"/path/to/package/",
"Location":[
"Saturn"
],
"Render":true
},
]
}
Pointers appreciated.
You can load the properties into an anonymous object and then serialize it. Something like this should work (untested):
An alternative to an anonymous object would be to use a Dictionary. But I think that the anonymous object will work rather nicely in this case.