Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import std.stdio;
- import std.string;
- import std.json;
- import std.regex;
- import std.typecons;
- import pegged.grammar;
- mixin(grammar(`
- QueryPath:
- Path <- Segment (:"." Segment)*
- Segment <- identifier
- `));
- class Predicate {
- string lhs;
- string op;
- string rhs;
- this(string lhs, string op, string rhs) {
- this.lhs = lhs;
- this.op = op;
- this.rhs = rhs;
- }
- }
- class Query {
- string[] sourceFields;
- string sourceNode;
- Predicate[] predicates;
- this(string[] sourceFields, string sourceNode, Predicate[] predicates) {
- this.sourceFields = sourceFields;
- this.sourceNode = sourceNode;
- this.predicates = predicates;
- }
- Nullable!JSONValue findBaseNode(JSONValue obj, string path) {
- ParseTree p = QueryPath(path);
- string[] segments = p.matches;
- Nullable!JSONValue current;
- foreach(segment;segments) {
- try {
- current = obj[segment];
- } catch (Exception e) {
- writeln(segment ~ " does not exist");
- current.nullify();
- return current;
- }
- }
- return current;
- }
- void f(JSONValue[string] objmap) {
- writeln("f obj");
- foreach(k,v;objmap) {
- if(v.type() == JSON_TYPE.ARRAY ||
- v.type() == JSON_TYPE.OBJECT) {
- writeln(k);
- filter(v);
- } else {
- writeln(k, "->", v);
- }
- }
- }
- void f(JSONValue[] objarray) {
- writeln("f array");
- }
- void filter(JSONValue obj) {
- // 1) if isAnon, then iterate each key like an array
- // isAnon should be sensitive to the segment
- switch(obj.type()) {
- case JSON_TYPE.ARRAY:
- writeln("ARRAY");
- auto a = obj.array();
- f(a);
- break;
- case JSON_TYPE.OBJECT:
- writeln("OBJECT");
- auto o = obj.object();
- f(o);
- break;
- default:
- writeln("WAT");
- }
- }
- void filter(JSONValue[string] objs) {
- writeln("FILTER MULTIPLE");
- foreach(o;objs) {
- writeln(">>> ", o);
- writeln("");
- }
- }
- bool isAnon() {
- bool anon = false;
- auto ctr = ctRegex!(`\$object`);
- foreach(f;sourceFields) {
- auto c = matchFirst(f, ctr);
- if(!c.empty) {
- return true;
- }
- }
- return false;
- }
- void exec(string jsonText) {
- JSONValue root = parseJSON(jsonText);
- writeln(root.type() == JSON_TYPE.OBJECT);
- auto base = findBaseNode(root, sourceNode);
- if(base.isNull) {
- writeln("No result");
- return;
- }
- writeln("Prefilter = ", base.get());
- bool anon = isAnon();
- if(anon) {
- filter(base.get());
- } else {
- filter(base.get());
- }
- }
- }
- void main()
- {
- File file = File("data.json", "r");
- string buf;
- while (!file.eof()) {
- string line = chomp(file.readln());
- buf ~= line;
- }
- Query q = new Query(["$object.block_size", "$object.kb_size"],
- "filesystem",
- [new Predicate("kb_available",">","1000")]);
- q.exec(buf);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement