Python實用庫

flatten-json: 將object, dict, array 壓縮成一維

一個有趣的用法:

from flatten_json import flatten


def __flatten(*args):
    a = []
    for e in args:
        if type(e) == type([]) or type(e) == type(()):
            a.append(__flatten(*e))
        elif type(e) == type({}):
            one_dict = flatten(e)
            b = []
            for key in one_dict:
                value = one_dict[key]
                b.append(f"{key}_{value}")
            a.append(" ".join(b))
        else:
            a.append(str(e))
    return " ".join(a)


print(__flatten("sss"))
print(__flatten(1))
print(__flatten([1, 2]))
print(__flatten((1, 2, [3, 4, (5, 6)])))
print(__flatten({"a": {"c": 1}}))
print(__flatten((1, 2, [3, 4, (5, 6, {"a": {"c": 1, "d": [2, 3, 4]}})])))

輸出:

sss
1
1 2
1 2 3 4 5 6
a_c_1
1 2 3 4 5 6 a_c_1 a_d_0_2 a_d_1_3 a_d_2_4
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章