扁平化 JSON 将嵌套对象转换为点号表示法的键。这对于数据库、电子表格和某些 API 格式至关重要。
什么是 JSON 扁平化?
嵌套 JSON:
{
"user": {
"name": "Alice",
"address": {
"city": "New York",
"zip": "10001"
}
},
"tags": ["admin", "dev"]
}
扁平化后:
{
"user.name": "Alice",
"user.address.city": "New York",
"user.address.zip": "10001",
"tags.0": "admin",
"tags.1": "dev"
}
扁平化实现
function flatten(obj, prefix = '') {
const result = {};
for (const [key, value] of Object.entries(obj)) {
const newKey = prefix ? ${prefix}.${key} : key;
if (value && typeof value === 'object' && !Array.isArray(value)) {
Object.assign(result, flatten(value, newKey));
} else {
result[newKey] = value;
}
}
return result;
}
反扁平化实现
function unflatten(obj) {
const result = {};
for (const [key, value] of Object.entries(obj)) {
const keys = key.split('.');
let current = result;
for (let i = 0; i < keys.length - 1; i++) {
current[keys[i]] = current[keys[i]] || {};
current = current[keys[i]];
}
current[keys[keys.length - 1]] = value;
}
return result;
}
使用场景
__ 或 _ 作为分隔符使用我们的 JSON 转 CSV 工具将扁平化的 JSON 导出到电子表格。