You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解析JSON键点字面量并转换为嵌套JSON结构?

解决扁平化JSON转嵌套结构的问题

嘿,这个情况我之前也遇到过!处理这种用点分隔键来表示嵌套结构的扁平化JSON,其实核心就是把每个带点的键拆分成层级,然后一步步构建嵌套对象就行。下面我给你两种常用语言的实现方案,直接就能用:

JavaScript 实现

function convertFlattenedJson(flatObj) {
  const nestedObj = {};
  
  // 遍历所有键值对
  for (const [key, value] of Object.entries(flatObj)) {
    // 跳过原数据里的空对象(比如description: {}、image: {})
    if (typeof value === 'object' && Object.keys(value).length === 0) {
      continue;
    }
    
    // 将带点的键拆分成层级数组
    const keyParts = key.split('.');
    let current = nestedObj;
    
    // 遍历层级(除了最后一个),创建嵌套对象
    for (let i = 0; i < keyParts.length - 1; i++) {
      const part = keyParts[i];
      // 如果当前层级不存在或不是对象,就初始化空对象
      if (!current[part] || typeof current[part] !== 'object') {
        current[part] = {};
      }
      current = current[part];
    }
    
    // 给最后一层的键赋值
    const lastPart = keyParts[keyParts.length - 1];
    current[lastPart] = value;
  }
  
  return nestedObj;
}

// 测试你的输入数据
const flatJson = { 
  "id": "def", 
  "name": "def", 
  "description": {}, 
  "description.shortened": "def", 
  "description.extended": "def", 
  "type": "EDIBLE_BOUQUET", 
  "image": {}, 
  "image.name": "def", 
  "image.slug": "def", 
  "image.extension": "PNG", 
  "state": "FEATURED", 
  "stock": "def" 
};

const nestedJson = convertFlattenedJson(flatJson);
console.log(JSON.stringify(nestedJson, null, 2));

Python 实现

import json

def convert_flattened_json(flat_obj):
    nested_obj = {}
    
    for key, value in flat_obj.items():
        # 跳过空字典
        if isinstance(value, dict) and not value:
            continue
        
        # 拆分键为层级列表
        key_parts = key.split('.')
        current = nested_obj
        
        # 构建嵌套层级
        for part in key_parts[:-1]:
            if part not in current or not isinstance(current[part], dict):
                current[part] = {}
            current = current[part]
        
        # 赋值最后一层
        current[key_parts[-1]] = value
    
    return nested_obj

# 测试输入
flat_json = { 
    "id": "def", 
    "name": "def", 
    "description": {}, 
    "description.shortened": "def", 
    "description.extended": "def", 
    "type": "EDIBLE_BOUQUET", 
    "image": {}, 
    "image.name": "def", 
    "image.slug": "def", 
    "image.extension": "PNG", 
    "state": "FEATURED", 
    "stock": "def" 
}

nested_json = convert_flattened_json(flat_json)
print(json.dumps(nested_json, indent=2))

逻辑说明

  1. 首先跳过原数据里的空对象(比如description: {}),因为这些空对象会被后续带点键的实际值覆盖,留着反而会干扰结果;
  2. 把每个带点的键拆分成层级数组(比如description.shortened拆成['description', 'shortened']);
  3. 遍历层级数组,一步步在目标对象里创建对应的嵌套结构,最后给最内层的键赋值;
  4. 这个方案是通用的,不管你的扁平化JSON有多少层嵌套,都能正确转换。

内容的提问来源于stack exchange,提问作者Ryan S.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:29:00