Haxe Code Cookbook
Haxe programming cookbookMacrosValidates a .JSON file compile-time

Validates a .JSON file compile-time

Reading time: 1 minute

Json is quite a strict format. Ensure all comma's and quotes are correct using a macro function, which is executed while compiling.

Macro function

class Validator {
  public static macro function validateJson(path:String) {
    if (sys.FileSystem.exists(path)) {
      var content = sys.io.File.getContent(path);
      try {
        // Test the json by parsing it. 
        // It will throw an error when you made a mistake.
      } catch (error:String) {
        // create position inside the json, FlashDevelop handles this very nice.
        var position = Std.parseInt(error.split("position").pop());
        var pos = haxe.macro.Context.makePosition({
            max:position + 1,
        haxe.macro.Context.error(path + " is not valid Json. " + error, pos);
    } else {
      haxe.macro.Context.warning(path + " does not exist", haxe.macro.Context.currentPos());
    return macro null;


This example only validates the .json files in debug builds and not in display mode (auto-completion). The function can be called from anywhere.

class Test {
  static function main() {
    #if (debug && !display)

Source: https://gist.github.com/markknol/59f0ede823f7d511362b

Last modified:
Category:  Macros