pythonjsontreeviewhdf5hyperspy

TreeView to JSON in Python


[Edit: apparently this file looks similar to h5 format] I am trying to extract metadata from a file with extension of (.dm3) using hyperspy in Python, I am able to get all the data but it's getting saved in a treeview, but I need the data in Json I tried to make my own parser to convert it which worked for most cases but then failed:

TreeView image

TreeView data generated

Is there a library or package I can use to convert the treeview to JSON in pyhton?

My parser:

def writearray(file,string):
    k = string.split('=')
    file.write('"' + k[0] + '":' + '[')
    for char in k[1]:
        file.write(char)
    file.write(']')

def writenum(file,string):
    k = string.split('=')
    file.write('"' + k[0] + '":' + k[1])

def writestr(file,string):
    k = string.split('=')
    file.write('"' + k[0] + '":' +'"'+ k[1]+'"')

def startnew(file,string):
    file.write('"'+string+'":'+'{\n')

def closenum(file,string):
    k = string.split('=')
    file.write('"' + k[0] + '":' + k[1] + '\n')
    file.write('},\n')

def closestr(file,string):
    k = string.split('=')
    file.write('"' + k[0] + '":' + '"' + k[1] + '"' + '\n')
    file.write('},\n')

def closearr(file,string):
    k = string.split('=')
    file.write('"' + k[0] + '":' + '[')
    for char in k[1]:
        file.write(char)
    file.write(']\n')
    file.write('},\n')

def strfix(string):
    temp = ''
    for char in string:
        if char != ' ':
            temp += char
    return temp

def writethis(file,string):
    stripped = strfix(string)
    if "=" in stripped:
        temp = stripped.split("=")
        if ',' in temp[1]:
            writearray(file,stripped)
        elif temp[1].isdigit() or temp[1].isdecimal():
            writenum(file,stripped)
        else:
            writestr(file,stripped)

def createMetaData(dm3file):
    txtfile = os.path.splitext(dm3file)[0] + '.txt'
    jsonfile = os.path.splitext(dm3file)[0] + '.json'
    s = hs.load(dm3file)
    s.original_metadata.export(txtfile)
    file1 = open(txtfile, 'r', encoding="utf-8")
    Lines = file1.readlines()
    k = []
    for line in Lines:
        k.append(line)
    L = []
    for string in k:
        temp = ''
        for char in string:
            if char.isalpha() or char.isdigit() or char == '=' or char == ' ' or char == '<' or char == '>' or char == ',' or char == '.' or char == '-' or char == ':':
                temp += char
        L.append(temp)
    file2 = open(jsonfile, 'w', encoding="utf-8")
    file2.write('{\n')
    for i in range(0, len(L) - 1):
        currentspaces = len(L[i]) - len(L[i].lstrip())
        nextspaces = len(L[i + 1]) - len(L[i + 1].lstrip())
        sub = nextspaces - currentspaces
        if i != len(L) - 2:
            if (sub == 0):
                writethis(file2, L[i])
                if '=' in L[i]:
                    file2.write(',\n')
                else:
                    file2.write('\n')
            elif sub > 0:
                startnew(file2, L[i])
            else:
                if sub == -3:
                    writethis(file2, L[i])
                    file2.write('\n},\n')
                elif sub == -7:
                    writethis(file2, L[i])
                    file2.write('\n}\n},\n')
        else:
            writethis(file2, L[i])
            file2.write('\n}\n}\n}\n}')
    file1.close()
    os.remove(txtfile)
enter code here

Solution

  • I wrote a parser for the tree-view format:

    from ast import literal_eval
    from collections import abc
    from more_itertools import peekable
    
    
    def parse_literal(x: str):
        try:
            return literal_eval(x)
        except Exception:
            return x.strip()
    
    
    def _treeview_parse_list(lines: peekable) -> list:
        list_as_dict = {}
        for line in (x.strip() for x in lines):
            raw_k, raw_v = line.split(' = ')
            list_as_dict[int(raw_k.split()[-1][1:-1])] = parse_literal(raw_v)
            peek = lines.peek(None)
            if '╚' in line or (peek is not None and '├' in peek):
                break
        list_as_list = [None] * (max(list_as_dict) + 1)
        for idx, v in list_as_dict.items():
            list_as_list[idx] = v
        return list_as_list
    
    
    def _treeview_parse_dict(lines: peekable) -> dict:
        node = {}
        for line in (x.strip() for x in lines):
            if ' = ' in line:
                raw_k, raw_v = line.split(' = ')
                node[raw_k.split()[-1]] = parse_literal(raw_v)
            elif '<list>' in line:
                node[line.split()[-2]] = _treeview_parse_list(lines)
            else:
                try:
                    idx = line.index('├')
                except ValueError:
                    idx = line.index('└')
                peek = lines.peek(None)
                if peek is not None and '├' in peek and idx == peek.index('├'):
                    node[line.split()[-1]] = {}
                else:
                    node[line.split()[-1]] = _treeview_parse_dict(lines)
            if '└' in line:
                break
        return node
    
    
    def treeview_to_dict(lines: abc.Iterable) -> dict:
        return _treeview_parse_dict(peekable(lines))
    

    Usage:

    with open('meta.txt') as f:
        d = treeview_to_dict(f)
    

    You can obtain the metadata as a JSON file using Python's built-in json library:

    import json
    
    with open('meta.txt') as txt_file:
        with open('meta.json', 'w') as json_file:
            json.dump(treeview_to_dict(txt_file), json_file, indent=4)
    

    I've added indent=4 to make the JSON file more human-readable, so that you can verify it against the original format. As far as I can tell they match up in a sensible way.

    As I've written this, it uses the third-party more_itertools.peekable class. If you can't use more_itertools, it shouldn't be too hard to implement that functionality yourself, or just refactor the code so that it is no longer necessary to look ahead.


    License:

    This is free and unencumbered software released into the public domain.

    Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means.

    In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ON INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

    For more information, please refer to https://unlicense.org