I use a lot of XML files on my most of my projects (Flash, Android or otherwise). I like the idea of having some configurations parameter on easily editable text files, and not having to re-compile a project just to change a behavior slightly; where I can, instead, just edit a configuration file, re-run the application and see it behave in a different way.
Recently, I started moving most of my the static data on some applications I build – data that would normally be inside a XML file – to JSON files instead. JSON files are less verbose, and just easier to edit and parse. This seemed like a smart move, until I realized something: JSON files cannot have comments. In my infinite ignorance, I was just assuming JS comments were going to work.
Several workarounds exist (and were suggested on Twitter to me) but in my opinion none of them are ideal. I especially dislike creating new, bogus or redundant properties.
Instead, what I’ve come up with on my own work is simply pre-parsing the JSON files I work with to remove JS-like comments from it prior to decoding a String as a JSON object. This is not ideal – the file won’t be a valid JSON file – but I think it’s the least inelegant way to deal with the problem. That’s also what Douglas Crockford suggests, which is somewhat strange given he’s the one who made the decision to keep comments out of the standard (for a good reason, but still).
Anyway, since I always use my own AssetLibrary
class to load and manage JSON files, I just had to add an easy String replacement prior to parsing the JSON file from the URLLoader
data. The code is simple, and looks like this (paraphrased [paracoded?] to be more readable):
public function getAsJSON():Object { // Object after loading var loadingObject:URLLoader = ... // Get raw data as String var data:String = loadingObject.data as String; // Delete comments using RegExp data = replace(/\/\*.*?\*\//sg, ""); // Finally, create and return JSON data return JSON.parse(data); }
The above code is ActionScript 3, but the implementation is simple enough that it can probably be easily applied to other languages.
give a shot at eden, not only the comments are parsed but you have the option to keep them for “metadata” kind of usage
https://code.google.com/p/edenrr/
ex:
var eden:EdenSerializer = new EdenSerializer();
eden.deserialize( source );
trace( eden.comments );