You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
59 lines
1.6 KiB
59 lines
1.6 KiB
#!/usr/bin/env python3
|
|
import json
|
|
from typing import Any, Dict, List, Set
|
|
|
|
def extract_headers(obj: Any, prefix: str = "", headers: Set[str] = None) -> Set[str]:
|
|
"""递归提取 JSON 的所有字段作为表头"""
|
|
if headers is None:
|
|
headers = set()
|
|
|
|
if isinstance(obj, dict):
|
|
for key, value in obj.items():
|
|
new_prefix = f"{prefix}.{key}" if prefix else key
|
|
extract_headers(value, new_prefix, headers)
|
|
elif isinstance(obj, list):
|
|
if obj:
|
|
# 用第一个元素来推断结构
|
|
first_item = obj[0]
|
|
if isinstance(first_item, (dict, list)):
|
|
# 如果是复杂对象,递归处理
|
|
extract_headers(first_item, f"{prefix}[0]", headers)
|
|
else:
|
|
# 如果是简单类型,用泛用名
|
|
headers.add(f"{prefix}")
|
|
else:
|
|
# 基础类型,添加当前路径
|
|
if prefix:
|
|
headers.add(prefix)
|
|
|
|
return headers
|
|
|
|
def main():
|
|
# 测试 JSON
|
|
json_str = '''
|
|
{
|
|
"name": "张三",
|
|
"contact": {
|
|
"email": "zhang@example.com",
|
|
"phone": "13800138000"
|
|
},
|
|
"tags": ["A", "B"]
|
|
}
|
|
'''
|
|
|
|
data = json.loads(json_str)
|
|
headers = sorted(extract_headers(data))
|
|
|
|
print("📊 Excel 表头列表:")
|
|
print("=" * 50)
|
|
for i, header in enumerate(headers, 1):
|
|
print(f"{i}. {header}")
|
|
print("=" * 50)
|
|
print(f"\n共 {len(headers)} 个表头")
|
|
|
|
# 也输出 CSV 格式
|
|
print("\n📋 CSV 格式:")
|
|
print(", ".join(headers))
|
|
|
|
if __name__ == "__main__":
|
|
main()
|
|
|