Skip to content

Instantly share code, notes, and snippets.

@juniperfdel
Last active March 29, 2022 12:58
Show Gist options
  • Save juniperfdel/e3cfd77b187cbfc7570e1f7fdc1fbf78 to your computer and use it in GitHub Desktop.
Save juniperfdel/e3cfd77b187cbfc7570e1f7fdc1fbf78 to your computer and use it in GitHub Desktop.
Convert a ROOT file to a JSON file when the structure is just a list of TTrees with PyROOT
import argparse
import json
import sys
from ROOT import TTree,TFile
def root_to_dict(in_file):
root_fp = TFile(in_file)
file_kl = root_fp.GetListOfKeys()
rv = {}
for key in file_kl:
c_tree = root_fp.Get(key.GetName())
if not isinstance(c_tree, TTree):
continue
tree_as_list = []
# get leaves info
leaf_info = [(tree_leaf.GetName(), tree_leaf.GetTypeName(), tree_leaf.GetLen(), tree_leaf) for tree_leaf in c_tree.GetListOfLeaves()]
# Iterate through entires
for entry_num in range(c_tree.GetEntries()):
c_tree.GetEntry(entry_num)
c_entry = {}
# Iterate through leafs
for leaf_name, leaf_type, n_vals, c_leaf in leaf_info:
if leaf_type == "Char_t":
c_entry[leaf_name] = [c_leaf.GetValueString(i) for i in range(n_vals)]
elif leaf_type in ("Int_t", "ULong64_t", "UInt_t", "UShort_t"):
c_entry[leaf_name] = [int(c_leaf.GetValue(i)) for i in range(n_vals)]
elif leaf_type in ("Float_t", "Double_t"):
c_entry[leaf_name] = [c_leaf.GetValue(i) for i in range(n_vals)]
else:
print("Unknown Type, Please Modify to accommodate ", leaf_type)
print("Go to https://root.cern.ch/doc/master/classTLeaf.html#a06e8bfb89e1dc6e32ed1709eaaa814f1 then \
select the specific TLeaf Type that holds this value to see if GetValue() or another function is best at parsing this particular Leaf Type")
sys.exit(0)
tree_as_list.append(c_entry)
rv[c_tree.GetName()] = tree_as_list
root_fp.Close()
return rv
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Convert a ROOT file to a JSON file")
parser.add_argument('filename', help='input root filename')
args = parser.parse_args()
out_dict = root_to_dict(args.filename)
with open(f"{args.filename.replace('.root','')}.json",'w') as fp:
json.dump(out_dict, fp, indent=2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment