fudge icon indicating copy to clipboard operation
fudge copied to clipboard

JSON Format Support for GNDS Data in Fudge

Open ahnaf-tahmid-chowdhury opened this issue 1 year ago • 0 comments

Question

I have been working with GNDS data and found the support for converting between ENDF and XML formats quite useful. However, I was wondering if there is any native support in Fudge for converting GNDS data to and from JSON format? JSON is a widely-used and convenient format for many applications, especially when integrating with other tools and pipelines.

Workaround

For now, I am using the following Python code to convert GNDS XML data to JSON format:

import xml.etree.ElementTree as ET
import json

def xml_to_dict(elem):
    d = {elem.tag: {} if elem.attrib else None}
    children = list(elem)
    if children:
        dd = {}
        for dc in map(xml_to_dict, children):
            for k, v in dc.items():
                if k in dd:
                    if not isinstance(dd[k], list):
                        dd[k] = [dd[k]]
                    dd[k].append(v)
                else:
                    dd[k] = v
        d = {elem.tag: dd}
    if elem.attrib:
        d[elem.tag].update(('@' + k, v) for k, v in elem.attrib.items())
    if elem.text:
        text = elem.text.strip()
        if children or elem.attrib:
            if text:
                d[elem.tag]['#text'] = text
        else:
            d[elem.tag] = text
    return d

def convert_gnds(xml_file, json_file):
    tree = ET.parse(xml_file)
    root = tree.getroot()
    gnds_dict = xml_to_dict(root)
    with open(json_file, 'w') as f:
        json.dump(gnds_dict, f, indent=2)

convert_gnds('gnds_data.xml', 'gnds_data.json')

ahnaf-tahmid-chowdhury avatar Oct 09 '24 17:10 ahnaf-tahmid-chowdhury