如何使用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
相关产品推荐
相关产品推荐

