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

基于Jolt规范字段名的硬编码值:JSON转换结果异常求助

解决Jolt JSON转换中基于字段名设置硬编码值的问题

我来帮你搞定这个Jolt转换需求!先明确你的输入和预期输出:

输入JSON

{ 
  "user":{ 
    "homePhone":"12345678901", 
    "mobilePhone":"12346750983", 
    "email":"test@example.com" 
  } 
}

预期输出JSON

{ 
  "contact":[ 
    { 
      "class":"PhoneClass", 
      "phoneNumber":"12345678901", 
      "mobile":false, 
      "preferred":false 
    }, 
    { 
      "class":"PhoneClass", 
      "phoneNumber":"12346750983", 
      "mobile":true, 
      "preferred":true 
    }, 
    { 
      "class":"EmailClass", 
      "email":"test@example.com" 
    } 
  ] 
}

正确的Jolt转换规范

你需要用shift操作来重新组织结构,同时通过#前缀来设置硬编码值(包括字符串和布尔值),以下是完整的Jolt Spec:

[
  {
    "operation": "shift",
    "spec": {
      "user": {
        "homePhone": {
          "$": "contact[0].phoneNumber",
          "#PhoneClass": "contact[0].class",
          "#false": "contact[0].mobile",
          "#false": "contact[0].preferred"
        },
        "mobilePhone": {
          "$": "contact[1].phoneNumber",
          "#PhoneClass": "contact[1].class",
          "#true": "contact[1].mobile",
          "#true": "contact[1].preferred"
        },
        "email": {
          "$": "contact[2].email",
          "#EmailClass": "contact[2].class"
        }
      }
    }
  }
]

规范细节解释

  • shift操作:核心作用是重新映射JSON的键值对结构,把原user下的字段分配到contact数组的对应位置。
  • 字段值映射:用$表示取当前字段的原始值,比如homePhone的值会被赋值给contact[0].phoneNumber。
  • 硬编码值设置:用#前缀来指定固定值:
    • 字符串类型:比如#PhoneClass直接把class字段设为"PhoneClass"
    • 布尔类型:Jolt中布尔值不需要加引号,直接写#true或#false就能生成布尔类型的字段值(不是字符串)
  • 数组索引:通过contact[0]、contact[1]、contact[2]明确指定每个元素在数组中的位置,保证顺序和预期一致。

把这个Spec放到Jolt转换器中运行,就能得到你想要的输出结果啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:11:09