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

如何使用Jolt修改JSON数组中多字段名称并移除指定字段

JSON字段重命名与移除的解决思路

以下是几种实用的实现方案:

1. Python 脚本实现

利用Python内置的json模块,读取输入JSON后遍历处理每个对象:

import json

# 输入JSON数据(也可从文件读取)
input_json = '''
{
  "12346565": [
    {
      "type": "13",
      "value": "3",
      "score": "5"
    },
    {
      "type": "45",
      "value": "1",
      "score": "5"
    }
  ],
  "12346777": [
    {
      "type": "41",
      "value": "10",
      "score": "3"
    }
  ]
}
'''

# 解析JSON
data = json.loads(input_json)
result = {}

# 遍历每个顶层键值对
for key, items in data.items():
    transformed_items = []
    for item in items:
        # 构建新对象:重命名字段并移除score
        transformed_item = {
            "model": item["type"],
            "v": item["value"]
        }
        transformed_items.append(transformed_item)
    result[key] = transformed_items

# 输出结果
print(json.dumps(result, indent=2))

2. jq 命令行工具实现

jq是专门处理JSON的命令行工具,一行命令即可完成转换:

# 假设输入数据存于input.json文件,输出到output.json
jq 'to_entries | map(.value = [.value[] | {model: .type, v: .value}]) | from_entries' input.json > output.json

解释:

  • to_entries:将顶层键值对转为{key, value}结构的数组
  • map(...):遍历每个条目,对value数组里的每个对象做字段映射
  • from_entries:将处理后的条目数组转回原JSON结构

3. JavaScript(Node.js/浏览器)实现

在JS环境中解析并处理JSON:

// 输入JSON字符串
const inputJson = `{
  "12346565": [
    {
      "type": "13",
      "value": "3",
      "score": "5"
    },
    {
      "type": "45",
      "value": "1",
      "score": "5"
    }
  ],
  "12346777": [
    {
      "type": "41",
      "value": "10",
      "score": "3"
    }
  ]
}`;

// 解析并处理
const data = JSON.parse(inputJson);
const result = {};

for (const key in data) {
  result[key] = data[key].map(item => ({
    model: item.type,
    v: item.value
  }));
}

// 输出结果
console.log(JSON.stringify(result, null, 2));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 19:31:02