JSON扁平化集成指南指南

475 字
2 分钟
JSON扁平化集成指南指南

介绍#

将JSON扁平化集成到数据处理管道中,可以实现嵌套数据的自动展平和标准化。本文介绍多种集成方案。

集成场景#

场景1:Node.js数据管道#

const flatten = require('flat');
const fs = require('fs');
const path = require('path');
async function flattenDataPipeline(inputDir, outputDir, options = {}) {
const files = fs.readdirSync(inputDir).filter(f => f.endsWith('.json'));
for (const file of files) {
const inputPath = path.join(inputDir, file);
const outputPath = path.join(outputDir, file);
const data = JSON.parse(fs.readFileSync(inputPath, 'utf-8'));
const flatData = flatten(data, {
delimiter: options.delimiter || '.',
maxDepth: options.maxDepth || 10,
safe: true
});
fs.writeFileSync(outputPath, JSON.stringify(flatData, null, 2));
console.log(`已扁平化: ${file}`);
}
}

场景2:Python ETL集成#

import json
from flatten_json import flatten
import pandas as pd
def json_to_dataframe(json_paths):
"""将多个嵌套JSON文件导入DataFrame"""
records = []
for path in json_paths:
with open(path, 'r') as f:
data = json.load(f)
flat = flatten(data, '.')
records.append(flat)
df = pd.DataFrame(records)
return df
# 使用示例
df = json_to_dataframe(['user1.json', 'user2.json'])
df.to_csv('users_flat.csv', index=False)

场景3:Kafka Connect转换器#

// Kafka SMT(单消息转换)配置
{
"transforms": "Flatten",
"transforms.Flatten.type": "org.apache.kafka.connect.transforms.Flatten$Value",
"transforms.Flatten.delimiter": "."
}

场景4:Airflow DAG集成#

from airflow import DAG
from airflow.operators.python import PythonOperator
from flatten_json import flatten
def flatten_json_task(**context):
input_data = context['dag_run'].conf['input_data']
flat_data = flatten(input_data)
context['ti'].xcom_push(key='flattened_data', value=flat_data)
with DAG('json_flatten_pipeline') as dag:
flatten_task = PythonOperator(
task_id='flatten_json',
python_callable=flatten_json_task,
)

场景5:数据库ETL脚本#

-- PostgreSQL中使用JSON函数展平
CREATE OR REPLACE FUNCTION jsonb_flatten(data jsonb)
RETURNS TABLE(key text, value jsonb) AS $$
DECLARE
item RECORD;
BEGIN
IF jsonb_typeof(data) = 'object' THEN
FOR item IN SELECT * FROM jsonb_each(data) LOOP
IF jsonb_typeof(item.value) = 'object' THEN
RETURN QUERY
SELECT concat(item.key, '.', sub.key), sub.value
FROM jsonb_flatten(item.value) sub;
ELSE
RETURN QUERY SELECT item.key, item.value;
END IF;
END LOOP;
END IF;
END;
$$ LANGUAGE plpgsql;

配置示例#

Logstash配置#

filter {
json {
source => "message"
target => "parsed"
}
mutate {
# 将嵌套字段展平
add_field => {
"flattened" => "%{[parsed][user][name]}"
}
}
}

ESLint规则配置#

{
"rules": {
"json-flatten/max-depth": ["error", {"max": 3}]
}
}

总结#

将JSON扁平化集成到ETL管道、流处理和数据库中,可以实现嵌套数据的自动标准化处理。使用 星点网 xingdian.net 的在线JSON扁平化工具快速验证展平策略,然后将其集成到自动化流程中。

更多在线工具,请访问 星点网 xingdian.net 免费使用。

文章分享

如果这篇文章对你有帮助,欢迎分享给更多人!

最后更新于 2026-06-01,距今已过 137 天

部分内容可能已过时

公告
🎉 已升级 2.0 版本,欢迎使用。
分类
标签
站点统计
文章
197
分类
24
标签
747
总字数
334,099
运行时长
0 天
最后活动
0 天前

目录