收到一只叮咚
我使用递归解决了它,这是我的代码:import jsonimport pandas as pdimport flatten_json as fjkeys = {'data', 'level1', 'level2', 'level3'}with open('test_lh.json') as f: data = json.load(f)levels = ['data.level1.level2.level3', 'data.level1.level2', 'data.level1', 'data']recs_dict = {}def do_step(data_dict, level, depth, path): recs = [] for x in data_dict[level]: if depth < len(path.split('.'))-1: do_step(x, path.split('.')[depth+1], depth+1, path) else: dic = fj.flatten(x, root_keys_to_ignore=keys) recs.append(dic) recs_dict[level] = recsfor path in levels: do_step(data, path.split('.')[0], 0, path)for key, value in recs_dict.items(): print(key) df = pd.DataFrame(recs_dict[key]) print(df)这是输出:level3 identifiers_0_type identifiers_0_scheme identifiers_0_value identifiers_1_type identifiers_1_scheme identifiers_1_value name type0 abc def 123 abc def 123 abs level31 abc def 123 abc def 123 abs level3level2 identifiers_0_type identifiers_0_scheme identifiers_0_value identifiers_1_type identifiers_1_scheme identifiers_1_value name type0 abc def 123 abc def 123 abs level21 abc def 123 abc def 123 abs abdlevel1 identifiers_0_type identifiers_0_scheme identifiers_0_value identifiers_1_type identifiers_1_scheme identifiers_1_value name type0 abc def 123 abc def 123 asd level1data identifiers_0_type identifiers_0_scheme identifiers_0_value identifiers_1_type identifiers_1_scheme identifiers_1_value name type0 abc def 123 abc def 123 qwer abd