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

如何解析TLV字符串并生成嵌套JavaScript对象?

问题

需要解析TLV字符串并生成嵌套对象,给定TLV字符串:

const text = 'AA06ClaireCC04JackBB03TomEE05James'

期望生成的嵌套对象结构:

{
  "Acrobatic Artist": {
    "AA": {
      "Claire": {
        "Curious Camper": {
          "CC": {
            "Jack": {
              "Baddest Banana": {
                "BB": {
                  "Tom": {
                    "Energetic Elephant": {
                      "EE": {
                        "James": "LASTRECORD"
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

当前实现代码:

const map = {
  AA: 'Acrobatic Artist',
  BB: 'Baddest Banana',
  CC: 'Curious Camper',
  DD: 'Desperate Driver',
  EE: 'Energetic Elephant'
}

function createJson(str) {
    let json = {}
    let remainingText = str

    while(remainingText.length > 0) {
       const tag = remainingText.substring(0, 2)
       const len = remainingText.substring(2, 4)
       const val = remainingText.substring(4, len)
       const offset = tag.length + len.length + parseInt(len, 16)

       remainingText = remainingText.substring(offset)
       console.log('new text: ' + remainingText)
    
       json[map[tag]] = {}
       json[map[tag]][tag] = {}
       json[map[tag]][tag][val] = {}
  }
  return json
}

但代码生成的是平级对象,不符合嵌套要求:

{
  "Acrobatic Artist": {
    "AA": { 
      "Claire": {} 
    }
  },
  "Baddest Banana": {
    "BB": { 
      "Tom": {} 
    }
  },
  "Curious Camper": {
    "CC": { 
      "Jack": {} 
    }
  },
  "Energetic Elephant": {
    "EE": { 
      "James": {} 
    }  
  }
}

注:可忽略示例中的LASTRECORD部分。

解决方案

核心问题是每次循环直接给根对象赋值,导致结构平级。需通过变量跟踪当前嵌套层级,将新结构挂载到上一层级的空对象中。

修改后的代码:

const map = {
  AA: 'Acrobatic Artist',
  BB: 'Baddest Banana',
  CC: 'Curious Camper',
  DD: 'Desperate Driver',
  EE: 'Energetic Elephant'
}

function createJson(str) {
    let root = {}
    let currentLevel = root // 跟踪当前嵌套的最内层对象
    let remainingText = str

    while(remainingText.length > 0) {
       const tag = remainingText.substring(0, 2)
       const lenHex = remainingText.substring(2, 4)
       const len = parseInt(lenHex, 16) // 将十六进制长度转为十进制
       const val = remainingText.substring(4, 4 + len) // 修复截取逻辑:结束索引=起始索引+长度
       const offset = 2 + 2 + len // 计算偏移量:标签(2位)+长度(2位)+值(len位)

       remainingText = remainingText.substring(offset)
    
       // 构建当前TLV对应的嵌套结构
       const tagAlias = map[tag]
       const currentStructure = {
         [tagAlias]: {
           [tag]: {
             [val]: {}
           }
         }
       }

       // 将当前结构挂载到上一层级
       Object.assign(currentLevel, currentStructure)
       // 更新当前层级为最内层空对象,供下一次嵌套使用
       currentLevel = currentStructure[tagAlias][tag][val]
  }
  return root
}

// 测试验证
const text = 'AA06ClaireCC04JackBB03TomEE05James'
console.log(JSON.stringify(createJson(text), null, 2))

关键调整说明:

  • 层级跟踪:新增currentLevel变量,始终指向当前嵌套的最内层空对象,确保新结构能正确嵌套进去
  • 截取逻辑修复:原代码substring(4, len)错误,应使用4 + len作为结束索引,保证值的截取准确
  • 结构挂载:通过Object.assign将当前TLV结构合并到上一层级,而非直接覆盖根对象

内容的提问来源于stack exchange,提问作者kzaiwo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 19:40:36