Json.parse(...) seems to return a String?


I’m attempting to read ‘room’-info from a Json file. At the moment, I’m just trying to figure out how everything works. The next step would be to create a small room-editor for the game.

This is some (exploratory) code :

var scene1 = Json.parse(Json.stringify('assets/json/scene1_rooms.json')); 
trace(Type.typeof(scene1)); // TClass([class String]) ???

I was expecting ‘Array’ as type, since this is (part of) my json-file :

	"bgImg" : "",
	"nav" : {
		"navL": 2
	"bgImg" : "",
	"nav" : {
		"navL": 3,
		"navR": 1

The Json-file is valid ; I have checked it with this class ‘util.Validator’ and also with an online validator.
However, when I try to do this :

var scene1:Array<Dynamic> = Json.parse(...) 

I get the following error :

//exception, information=TypeError: Error #1034: Type Coercion failed: cannot convert "assets/json/scene1_rooms.json" to Array.

What am I doing wrong here ??? :confused:

Here’s your problem. Json.stringify() doesn’t involve any file I/O at all. All it does is takes an object and turns it into a JSON-formatted string. For example:

var object:Dynamic = {};
object.a = 0;
object.b = 65535;

trace(haxe.Json.stringify(object)); //{"a":0,"b":65535}

For file I/O, you’ll want to use OpenFL’s assets system:

var scene1 = Json.parse(Assets.getText('assets/json/scene1_rooms.json'));
1 Like

Oooohhhh !

Problem solved !
Thanks, I would never have been able to figure this out by myself !

I got confused because Json.parse() requires a string, and technically (in my mind anyway), the contents of my Json-file isn’t a string (no ’ or "), so I used Json.stringify() to ‘fix’ the problem :blush: