Last active
September 28, 2015 18:38
-
-
Save jdonaldson/1480207 to your computer and use it in GitHub Desktop.
Create compile-time typed objects from arbitrary json strings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#build file | |
-lib hxjson2 | |
-main Jsonify | |
-x bin/jsonify.n | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#if macro | |
import haxe.macro.Expr; | |
import haxe.macro.Context; | |
import hxjson2.JSON; | |
import haxe.Http; | |
import neko.FileSystem; | |
#end | |
class Jsonify { | |
public static function main(){ | |
trace(jsonify("http://api.twitter.com/1/users/lookup.json?screen_name=haxelang")); | |
// trace(jsonify("assets/gdithub.json").commits[0]); // e.g. a file on your disk | |
} | |
@:macro public static function jsonify(e:Expr){ | |
var loc = ''; | |
var str = ''; | |
switch(e.expr){ | |
case EConst(c): switch (c){ | |
case Constant.CString(s): loc = s; | |
default: throw 'not a string!'; | |
} | |
default: throw 'not a constant!'; | |
} | |
if (~/^ *http:\/\//.match(loc)){ | |
str = Http.requestUrl(loc); | |
} else if (FileSystem.exists(loc)){ | |
str = neko.io.File.read(loc).readAll().toString(); | |
} else { | |
throw 'not a file or url!'; | |
} | |
var json = JSON.decode(str); | |
var expr = Context.makeExpr(json,e.pos); | |
return expr; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment