How to loop through each item of a json array?

I have a .json file that I am using to have data for each level. I have an array in the .json file that i need to loop through the data for a level to generate it, except when i use this:

for(i in leveldata){
    loadLevel(levelData[i]);
}

it gives an error saying You can't iterate on a Dynamic value, please specify Iterator or Iterable
I read a lot about iterators/iterables, but yet can’t figure out what it means

You need to hint the type of your json data.
For example:

var leveldata:Array<{structure of your level data}> = Json.parse(data);
for(i in leveldata) {...}

Otherwise compiler doesn’t know how to handle your leveldata. Whether it’s Iterable or Iterator.

This tool helps generating typedefs from a json example, it can be handy for a quick start.

There’s a neat macro trick to automatically get the json object in haxe:

Normally you load the json file with something like this:

var json = haxe.Json.parse(sys.io.File.getContent(path));

Instead, if you load the json in a macro, then the json data will be available at compile-time and therefore the types will be known:

Create a file called JsonMacro.hx (or whatever you like) and add this:

macro function load(path: String) {
	return try {
		var json = haxe.Json.parse(sys.io.File.getContent(path));
		macro $v{json};
	} catch(e) {
		haxe.macro.Context.error('Failed to load json: $e', haxe.macro.Context.currentPos());
	}
}

Then use this to load your json instead:

var leveldata = JsonMacro.load('leveldata.json');

for (i in leveldata.array) { // works now because we know the type of the leveldata object
}
5 Likes

George, this macro trick would be a great addition to code.haxe.org.
If you don’t put it there, I’ll do it (if ok for you - all credits to you, of course!).

Hey @cambiata, I’ll make a PR now – to save time it will be pretty much the post as-is with some minor tweaks but feel free to change anything to make it work better for the site

Edit: Opened PR: Add strictly-typed JSON macro article by haxiomic · Pull Request #161 · HaxeFoundation/code-cookbook · GitHub

1 Like