Ben Biddington

Whatever it is, it's not about "coding"

Posts Tagged ‘json

Top n javascript gotchas

leave a comment »

Recently we have discovered one or two Javascript quirks.

New lines in variable assignment

Javascript treats new lines as the end of a statement in some cases. For example, declaring a string variable:

This one works:

var result = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. " +
    "Etiam at tortor ac sapien ultricies cursus. " +
    "Vivamus sed mi vitae urna auctor consectetur."

While this one will result in an error:

var result =
    "Lorem ipsum dolor sit amet, consectetur adipiscing elit. " +
    "Etiam at tortor ac sapien ultricies cursus. " +
    "Vivamus sed mi vitae urna auctor consectetur."

Json object declarations, commas and browser support

We encountered a problem with Internet Explorer. Care needs to be taken when declaring objects using json. Internet Explorer baulks at extra commas, the following will fail due to the extra comma after the result.count declaration.

var result = {
    name: "A test",
    count:0, // [!] THIS COMMA IS NOT ALLOWED
}

Neither Chrome nor Firefox complained.

We tracked this down using grep, something like this will find occurences:

$ grep -Plir ',[\s]*\}' * --include=*.js

One side issue with that was when the sequence occurs on the same line as the NUL character identifying the end of file.

This one matches:

this-one-will-match

While this one does not:

this-one-will-not

References

  • Json memo
    The application/json Media Type for JavaScript Object Notation (JSON). provides information for the Internet community. It does
    not specify an Internet standard of any kind. Distribution of this
    memo is unlimited.
  • Json Lint
    An online validator for json.

Written by benbiddington

25 March, 2009 at 11:46