I made a little code gen and was wondering if I should go to the trouble of handling the extra comma at the end. IE seems to ignore it, but I need to keep it cross browser, and I’d like to generate valid code anyway.
function init() {
var myOptions = { : 'Select home value', // <== THERE'S THE NON EXISTANT KEY
100000 : '$90,001 - $100,000',
1000000 : '$950,001 - $1,000,000',
1000001 : 'Over $1,000,000', // <== HERE'S THE COMMA I'M CURIOUS ABOUT
};
here’s the code to generate
protected string DoTransform()
{
var sb = new StringBuilder("var myOptions = {");
foreach (var option in
XDocument.Load(MapPath("~/App_Data/Data.xml"))
.XPathSelectElements("./data/options[@question='ApproximatePropertyValue']/option"))
{
sb.AppendFormat("{0} : '{1}',\n", option.Attribute("value").Value, option.Value);
}
sb.AppendLine("};");
return sb.ToString();
}
ANSWER:
Here’s the updated code that takes care of the empty key (by skipping the first element) and trailing comma (by rearranging logic so TrimEnd can nab it).
protected string DoTransform()
{
var sb = new StringBuilder();
foreach (var option in
XDocument.Load(MapPath("~/App_Data/Data.xml"))
.XPathSelectElements("./data/options[@question='ApproximatePropertyValue']/option")
.Skip(1))
{
sb.AppendFormat("{0}:'{1}',", option.Attribute("value").Value, option.Value);
}
return"var myOptions = {\n" + sb.ToString().TrimEnd(',') + "};";
}
My understanding is that most browsers will allow the trailing comma, but it is not something which is acceptable in the JSON spec, so it is a
bad idea. On the other hand, the fact that you are missing a key in that first key-value pair won’t be forgiven… by ANYONE 😉Edit
Just saw your code above. Forgive me, my .NET is rusty (as in, I’ve barely looked at it, ever), but I believe this will work: