JSON Flattener
将嵌套JSON展平为带有点号表示法的平面键值对。
关于此工具
JSON 扁平化是将嵌套的 JSON 结构转换为使用点符号键的单层表示的过程。当您处理来自 API、数据库或配置文件的复杂嵌套对象时,此工具将它们转换为简单的键值对,便于分析、存储或导出为 CSV 或电子表格等格式。
要使用 JSON Flattener,只需将嵌套的 JSON 粘贴到输入区域,然后单击扁平化按钮。该工具立即将多级对象和数组转换为扁平化的键,其中父子关系由点表示,例如"user.profile.email"。然后,您可以直接复制结果,或将其导出以用于数据管道、报告工具或电子表格应用程序。
此工具对于转换非结构化 API 响应的数据工程师、调试复杂对象结构的开发人员以及为期望扁平化模式的 BI 平台准备数据的分析师极具价值。JSON Flattener 支持数组索引和自定义分隔符,使其能够灵活地用于各种数据转换工作流。
常见问题
代码实现
def flatten(obj, prefix="", sep="."):
"""Flatten a nested dict into dot-notation keys."""
result = {}
if isinstance(obj, dict):
for key, value in obj.items():
new_key = f"{prefix}{sep}{key}" if prefix else key
if isinstance(value, (dict, list)):
result.update(flatten(value, new_key, sep))
else:
result[new_key] = value
elif isinstance(obj, list):
for i, value in enumerate(obj):
new_key = f"{prefix}{sep}{i}" if prefix else str(i)
if isinstance(value, (dict, list)):
result.update(flatten(value, new_key, sep))
else:
result[new_key] = value
else:
result[prefix] = obj
return result
def unflatten(flat, sep="."):
"""Reconstruct nested dict from dot-notation keys."""
result = {}
for key, value in flat.items():
parts = key.split(sep)
d = result
for part in parts[:-1]:
d = d.setdefault(part, {})
d[parts[-1]] = value
return result
# Example
nested = {"user": {"name": "Alice", "address": {"city": "Seoul"}}}
flat = flatten(nested)
print(flat) # {'user.name': 'Alice', 'user.address.city': 'Seoul'}
print(unflatten(flat)) # back to nestedComments & Feedback
Comments are powered by Giscus. Sign in with GitHub to leave a comment.