You’d use these [0] functions to build a json string and return your structure, one row per root of each hierarchy (you might only return one row if you’re after a single hierarchical json object).
[0] https://www.postgresql.org/docs/9.5/static/functions-json.ht...