def parse_tree_to_sql_where(parse_tree):
    """
    Walks a parse tree of a filter expression and generates a Postgres WHERE
    clause from it
    """
    def next_element():
        if len(parse_tree) > 0:
            return parse_tree.pop(0)

    where_clause = '('
    cur = next_element()

    while cur:
        if isinstance(cur, str):
            where_clause += str(cur)
            if len(parse_tree) > 0:
                where_clause += ' '
        else:
            if 'token_type' in cur and cur['token_type'] in ('fieldname', 'value'):
                if cur['token_type'] == 'fieldname':
                    where_clause += 'data->>\'' + str(cur[0]) + '\''
                else:
                    where_clause += str(cur[0])

                if len(parse_tree) > 0:
                    where_clause += ' '
            else:
                where_clause += parse_tree_to_sql_where(cur)
                if len(parse_tree) > 0:
                    where_clause += ' '

        cur = next_element()

    where_clause += ')'

    return where_clause