的
flatten_json
def flatten_json(nested_json: dict, exclude: list=[''], sep: str='_') -> dict:
"""
Flatten a list of nested dicts.
"""
out = dict()
def flatten(x: (list, dict, str), name: str='', exclude=exclude):
if type(x) is dict:
for a in x:
if a not in exclude:
flatten(x[a], f'{name}{a}{sep}')
elif type(x) is list:
i = 0
for a in x:
flatten(a, f'{name}{i}{sep}')
i += 1
else:
out[name[:-1]] = x
flatten(nested_json)
return out
使用递归展平嵌套的dicts
data
的嵌套程度如何?:
flatten_json
被用来解压一个超过100000列的文件
扁平化的JSON可以不扁平化吗?:
- 是的,这个问题不包括这个。但是,如果您安装了
flatten
包,则有一个unflatten
方法,但我尚未对其进行测试李>
Tags:
如何展平
JSON
或dict
是一个常见的问题,有很多答案。flatten_json
递归地展平嵌套的dict
或JSON
李>假设:
JSON
或dict
加载到某个变量(例如文件、api等)中data
如何将
data
加载到flatten_json
:dict
,如函数类型提示所示李>最常见的
data
:{}
flatten_json(data)
[{}, {}, {}]
[flatten_json(x) for x in data]
{1: {}, 2: {}, 3: {}}
[flatten_json(data[key]) for key in data.keys()]
{'key': [{}, {}, {}]}
:[flatten_json(x) for x in data['key']]
实例:
data
展平为pandas.DataFrame
进行进一步分析。import pandas as pd
加载pandas
flatten_json
返回一个dict
,可以使用csv
包直接保存李>数据1:
展平1:
数据2:
展平2:
数据3:
展平3:
其他例子:
相关问题 更多 >
编程相关推荐