def to_json(t):
    """
    converts a tree to JSON-export data,
    using the specified encoding for
    non-unicode strings
    """
    terms = []
    for n in t.terminals:
        if n.parent:
            parent_id = n.parent.id
        else:
            parent_id = '0'
        extras = []
        if hasattr(n, 'secedge') and n.secedge is not None:
            extra = []
            for secedge in n.secedge:
                tgt = secedge[1]
                if tgt.isTerminal():
                    tgt_id = tgt.start
                else:
                    tgt_id = tgt.id
                extra.append([secedge[0], tgt_id])
            if extra:
                extras = [extra]
        terms.append([n.word, n.cat, n.morph, n.edge_label, parent_id,
            getattr(n, 'lemma', None)] + extras)
    nonterms = []
    all_nodes = sorted(t.node_table.values(), key=lambda n: n.id)
    for n in all_nodes:
        if n.parent:
            parent_id = n.parent.id
        else:
            parent_id = '0'
        extras = []
        if hasattr(n, 'secedge') and n.secedge is not None:
            extra = []
            for secedge in n.secedge:
                tgt = secedge[1]
                if tgt.isTerminal():
                    tgt_id = tgt.start
                else:
                    tgt_id = tgt.id
                extra.append([secedge[0], tgt_id])
            if extra:
                extras = [extra]
        nonterms.append([n.id, n.cat, n.attr, n.edge_label, parent_id] + extras
            )
    result = {'terminals': terms, 'nonterminals': nonterms}
    if hasattr(t, 'sent_no'):
        result['_id'] = str(t.sent_no)
    return result
