Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Converts a newick file into JSON format for d3/TreeWidget javascript component
import sys
from ete2 import Tree
import random
def get_json(node):
# Read ETE tag for duplication or speciation events
if not hasattr(node, 'evoltype'):
dup = random.sample(['N','Y'], 1)[0]
elif node.evoltype == "S":
dup = "N"
elif node.evoltype == "D":
dup = "Y" ="'", '')
json = { "name":,
"duplication": dup,
"branch_length": str(node.dist),
"seq_length": 0,
"type": "node" if node.children else "leaf",
"uniprot_name": "Unknown",
if node.children:
json["children"] = []
for ch in node.children:
return json
if __name__ == '__main__':
if len(sys.argv) > 1:
t = Tree(sys.argv[1])
# create a random example tree
t = Tree()
t.populate(100, random_branches=True)
# TreeWidget seems to fail with simple quotes
print str(get_json(t)).replace("'", '"')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment