COMMUNITY

Passing parameters to a macro gives error: haxe.macro.Expr should be String

EDIT:
I found another solution for what I was trying to do in the very firts place, and the reason I did try to use a macro.

The thing i was tryng to do was to load a .json file from a var.

The solution that worked in the end is the following:

var json_file: String = "assets/data/file.json";

data = Json.parse( Assets.getText( json_file ) );

Hi,

I’m trying to parse a .json file and found this solution [haxe - Load a JSON object from a file - Stack Overflow],
that works, only if you pass the file path as a string, directly to the macro, like:

/// This works
Config.json("assets/data/file.json");

But if you pass it a var it doesn’t works, I get this error:

/// This doesn't work
var test: String = "assets/data/file.json";
parsedJson = Config.json(test);

haxe.macro.Expr should be String

Any help?

Thanks in advance.

/// The Macro
class Config 
{
	macro public static function json(path: String) {
		var value = sys.io.File.getContent(path),
		json = haxe.Json.parse(value);
		return macro $v{json};
	}
}

Macros are run at compile time, if you do Config.json(test) the macro receive an argument “identifier named test” and can’t do anything with that, that macro can only receive string literals directly.

1 Like

Hej,

You can also do something like that ExprTools.getValue( Context.getTypedExpr( Context.typeExpr( expr ) ) ); to evaluate a constant : Try Haxe !

static inline var file	= "test.json";
  static function main() {
    Macro.json( file );
  }
1 Like

Thanks, I found another solution for what I was trying to do in the very firts place, and the reason I did try to use a macro.

The thing i was tryng to do was to load a .json file from a var.

The solution that worked in the end is the following:

var json_file: String = "assets/data/file.json";

data = Json.parse( Assets.getText( json_file ) );

Hej,
Here you’re using openFL. You can also do the same in pure Haxe using resources, take a look here : Resources - Haxe - The Cross-platform Toolkit

One alternative is you can embed a resource, within your code ( does not need openfl or any toolkit ), I use it on my ‘letters’ repo canvas experiment heavily.
In your hxml file.

-resource assets/data/file.json@myFile

then in haxe

var j: MyFileTdef = haxe.Json.parse( haxe.Resource.getString(myFile));

In haxe js I have a textloader I use for runtime loading, which can be useful.
https://github.com/nanjizal/htmlHelper/blob/master/src/htmlHelper/tools/TextLoader.hx
alternatively I use my ‘folder’ library on c++/neko for runtime loading
https://github.com/nanjizal/folder/blob/master/folder/Folder.hx
for openfl mac apps the path may needs to get outside the app container so some extra …/ are needed for loading files outside your app which differs from win.