Skip to content

Instantly share code, notes, and snippets.

@jdonaldson
Last active September 28, 2015 18:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jdonaldson/1480207 to your computer and use it in GitHub Desktop.
Save jdonaldson/1480207 to your computer and use it in GitHub Desktop.
Create compile-time typed objects from arbitrary json strings
#build file
-lib hxjson2
-main Jsonify
-x bin/jsonify.n
#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