精慕HU
过去我不得不做这种事情几次(将嵌套的 json 弄平)我将解释我的过程,你可以看看它是否有效,或者至少可以稍微处理一下代码以适应您的需求。1)接受data响应,并使用函数将其完全扁平化。当我第一次不得不这样做时,这个博客非常有帮助。2) 然后它遍历创建的平面字典,通过嵌套部分内的新键名称的编号来查找需要创建每一行和列的位置。还有一些键是唯一/不同的,所以它们没有一个数字来标识为“新”行,所以我在我称之为special_cols.3)当它遍历这些时,拉出指定的行号(嵌入在那些平面键中),然后以这种方式构造数据帧。这听起来很复杂,但是如果您逐行调试和运行,您就可以看到它是如何工作的。尽管如此,我相信它应该可以满足您的需求。data = {'took': 476, '_revision': 'r08badf3', 'response': {'accounts': {'hits': [{'name': '4002238760', 'display_name': 'Googleglass-4002238760', 'selected_fields': ['Googleglass', 'DDMonkey', 'Papu New Guinea', 'Jonathan Vardharajan', '4002238760', 'DDMadarchod-INSTE', None, 'Googleglass', '0001012556', 'CC', 'Setu Non Standard', '40022387', 320142, 4651321321333, 1324650651651]}, {'name': '4003893720', 'display_name': 'Swift-4003893720', 'selected_fields': ['Swift', 'DDMonkey', 'Papu New Guinea', 'Jonathan Vardharajan', '4003893720', 'DDMadarchod-UPTM-RemotexNBD', None, 'S.W.I.F.T. SCRL', '0001000110', 'SE', 'Setu Non Standard', '40038937', 189508, 1464739200000, 1559260800000]}]}}}import pandas as pdimport redef flatten_json(y): out = {} def flatten(x, name=''): if type(x) is dict: for a in x: flatten(x[a], name + a + '_') elif type(x) is list: i = 0 for a in x: flatten(a, name + str(i) + '_') i += 1 else: out[name[:-1]] = x flatten(y) return outflat = flatten_json(data) results = pd.DataFrame()special_cols = []columns_list = list(flat.keys())for item in columns_list: try: row_idx = re.findall(r'\_(\d+)\_', item )[0] except: special_cols.append(item) continue column = re.findall(r'\_\d+\_(.*)', item )[0] column = column.replace('_', '') row_idx = int(row_idx) value = flat[item] results.loc[row_idx, column] = valuefor item in special_cols: results[item] = flat[item]输出:print (results.to_string()) name displayname selectedfields0 selectedfields1 selectedfields2 selectedfields3 selectedfields4 selectedfields5 selectedfields6 selectedfields7 selectedfields8 selectedfields9 selectedfields10 selectedfields11 selectedfields12 selectedfields13 selectedfields14 took _revision0 4002238760 Googleglass-4002238760 Googleglass DDMonkey Papu New Guinea Jonathan Vardharajan 4002238760 DDMadarchod-INSTE NaN Googleglass 0001012556 CC Setu Non Standard 40022387 320142.0 4.651321e+12 1.324651e+12 476 r08badf31 4003893720 Swift-4003893720 Swift DDMonkey Papu New Guinea Jonathan Vardharajan 4003893720 DDMadarchod-UPTM-RemotexNBD NaN S.W.I.F.T. SCRL 0001000110 SE Setu Non Standard 40038937 189508.0 1.464739e+12 1.559261e+12 476 r08badf3