Creating types from json samples

Hi,
I’m trying to avoid writing boilerplate code that transforms json data into typed values. Did my homework and researched thoroughly, but couldn’t spot a library that helps with that. Found one for typescript though, that does just what I need - you give it some json samples, and it generates all the types needed.

Question is: do we have some library I couldn’t find? If not, how would you go about creating one?

Thanks in advance!

I think you can generate ts types from the tool you mention and then use ts2hx.

There are macros for that.

I’m not sure if I’m allowed to distribute the one I am using, but it’s not much (~150 loc for the whole thing). It takes a json at compile time and make the data (nested data too) available via static inline vars and internal types (so completion works). It’s only meant for static data, though.

It doesn’t even have to be a macro. One could write a simple script that parses the json using haxe.Json.parse, determines value types (using Type.typeof and/or Std.is) from that, constructs an anonymous structure definition as haxe.macro.Expr.TypeDefinition and then prints it out using new haxe.macro.Printer().printTypeDefinition. Sounds like a nice exercise for a Haxe enthusiast :slight_smile:

2 Likes

Andy shared a nice trick using $type() in this thread, and made an example in try haxe.

1 Like

There it is Haxe Json def :slight_smile:

3 Likes

yes I did that :stuck_out_tongue: GitHub - MatthijsKamstra/hxjsondef: HxJsonDef is command-line app written in Haxe that helps you quickly define a typedef from some arbitrary .json

2 Likes