laforge has uploaded this change for review. ( https://gerrit.osmocom.org/c/pysim/+/27163 )
Change subject: tlv: Function for flattening the list-of-dict output of TLV decoder ......................................................................
tlv: Function for flattening the list-of-dict output of TLV decoder
Before: { "FcpTemplate": [ { "FileDescriptor": { "shareable": true, "file_type": "df", "structure": "no_info_given" } }, { "FileIdentifier": "3f00" }, { "ProprietaryInformation": [ { "UiccCharacteristics": "71" }, { "AvailableMemory": 123052 } ] }, { "LifeCycleStatusInteger": "operational_activated" }, { "SecurityAttribReferenced": { "ef_arr_file_id": "2f06", "ef_arr_record_nr": 2 } }, { "PinStatusTemplate_DO": [ { "PS_DO": "40" }, { "KeyReference": 1 }, { "KeyReference": 129 } ] }, { "TotalFileSize": 187809 } ] }
After: { "FcpTemplate": { "FileDescriptor": { "shareable": true, "file_type": "df", "structure": "no_info_given" }, "FileIdentifier": "3f00", "ProprietaryInformation": { "UiccCharacteristics": "71", "AvailableMemory": 123052 }, "LifeCycleStatusInteger": "operational_activated", "SecurityAttribReferenced": { "ef_arr_file_id": "2f06", "ef_arr_record_nr": 2 }, "PinStatusTemplate_DO": { "PS_DO": "40", "KeyReference": 129 }, "TotalFileSize": 187809 } }
Change-Id: Ia5ad8f1d3b0d47ebdb1856b0feaba120bad3eef9 --- M pySim/tlv.py M pySim/ts_102_221.py 2 files changed, 28 insertions(+), 1 deletion(-)
git pull ssh://gerrit.osmocom.org:29418/pysim refs/changes/63/27163/1
diff --git a/pySim/tlv.py b/pySim/tlv.py index ba1aa9f..71338ab 100644 --- a/pySim/tlv.py +++ b/pySim/tlv.py @@ -404,3 +404,30 @@
def to_tlv(self): return self.to_bytes() + + +def flatten_dict_lists(inp): + """hierarchically flatten each list-of-dicts into a single dict. This is useful to + make the output of hierarchical TLV decoder structures flatter and more easy to read.""" + def are_all_elements_dict(l): + for e in l: + if not isinstance(e, dict): + return False + return True + + if isinstance(inp, list): + if are_all_elements_dict(inp): + # flatten into one shared dict + newdict = {} + for e in inp: + key = list(e.keys())[0] + newdict[key] = e[key] + inp = newdict + # process result as any native dict + return {k:flatten_dict_lists(inp[k]) for k in inp.keys()} + else: + return [flatten_dict_lists(x) for x in inp] + elif isinstance(inp, dict): + return {k:flatten_dict_lists(inp[k]) for k in inp.keys()} + else: + return inp diff --git a/pySim/ts_102_221.py b/pySim/ts_102_221.py index b9a94b7..3f8c49d 100644 --- a/pySim/ts_102_221.py +++ b/pySim/ts_102_221.py @@ -794,7 +794,7 @@ """ETSI TS 102 221 Section 11.1.1.3""" t = FcpTemplate() t.from_tlv(h2b(resp_hex)) - return t.to_dict() + return flatten_dict_lists(t.to_dict())
@staticmethod def match_with_card(scc: SimCardCommands) -> bool: