Http outcall response JSON processing in Motoko

I have encountered the same problem without having found a ready-made solution. So I wrote a parser that allows me to recover the value of a json object. It works in my use case but you can use it as inspiration :

public func parseValue(json : Text, obj : Text) : async Text {
        var r : Text = "";
        let b : Buffer.Buffer<Text> = Buffer.Buffer(1);
        for (e in Text.split(json, #text "[")) {
            if (Text.contains(e, #text obj)) {
                for (o : Text in Text.split(e, #text "{")) {
                    var j : Text = Text.replace(o, #text "}", "");
                    j := Text.replace(j, #text "]", "");
                    if (Text.endsWith(j, #text ",")) {
                        j := Text.trimEnd(j, #text ",");
                    };
                    for (f : Text in Text.split(j, #text ",")) {
                        if (Text.contains(f, #text obj)) {
                            for (t : Text in Text.split(f, #text ":")) {
                                switch (Text.contains(t, #text obj)) {
                                    case (false) {
                                        b.add(Text.replace(t, #text "\"", ""));
                                    };
                                    case (true) {};
                                };
                            };
                        };
                    };
                };
            };
        };
        r := b.get(b.size() - 1);
        return r;
    };
2 Likes