Tip for Working with JSON Lists
JSON - the JavaScript Object Notation - is a very neat way of generating object graphs concisely in java. I’ve recently used it in conjunction with JSPs to generate some data dynamically, and was rather pleased to see that it allows lists to be defined with a trailing comma, like this:
1,
2,
3,
];
(See the little comma after the number 3? Perl allows this too.) This is no big deal when writing data by hand, but nice for programmatic generation, as there’s no need to test whether you’re entering the loop for the last time, and, if so, omit the comma.
However, there’s a catch…
On Internet Explorer, the meaning of [1,2,3,] and [1,2,3] are subtley different: in the former case, it defines a list of four elements, the last one being null. On Firefox, both statements define a three-element list.
Here’s a quick test page to prove it for those who want to test it out for themselves, and see the error dialog in IE on the final pass of the loop:
<head>
<script type=’text/javascript’>
var data=[
{name:’abe’,age:37},
{name:’ced’,age:42},
];
window.onload=function(){
document.body.appendChild(
document.createTextNode(data.length+” data items:: “)
);
for (var i=0;i<data.length;i++){
var datum=data[i];
var txt=datum.name+” :: “+datum.age+”, “;
document.body.appendChild(document.createTextNode(txt));
}
}
</script>
</head>
<body>
</body>
</html>