使用Groovy语言实现n个JSON文件批量合并的解决方案咨询
手动指定任意数量文件的合并方案
你可以直接把所有待合并的JSON文件路径放入同一个列表,无需硬编码单个路径变量,兼容你原有直接拼接文件内容的逻辑,示例代码如下:
// 此处可填入任意数量的待合并JSON文件路径 def fileLocations = [ '/path/to/first.json', '/path/to/second.json', '/path/to/third.json', // 按需继续添加更多路径即可 ] // 合并后文件的存储路径 def mergeJsonFileLink = '/path/to/merged_output.json' def mergeFile = new File(mergeJsonFileLink) // 先清空目标文件原有内容,避免重复追加 mergeFile.text = '' fileLocations.each { filePath -> def currentFile = new File(filePath) // 加校验避免无效路径报错 if (currentFile.exists() && currentFile.isFile()) { mergeFile.append(currentFile.getText()) // 如果需要每个文件内容之间加分隔换行,可取消下面一行的注释 // mergeFile.append('\n') } } println("共处理${fileLocations.size()}个文件,合并JSON已生成")
自动批量合并目录下所有JSON文件的方案
如果待合并的JSON文件都存放在同一个目录下,可以直接遍历目录自动筛选JSON文件,无需手动逐个填写路径:
// 存放所有待合并JSON文件的目录路径 def jsonDirPath = '/path/to/your_json_folder' def mergeJsonFileLink = '/path/to/merged_output.json' def mergeFile = new File(mergeJsonFileLink) mergeFile.text = '' // 自动筛选目录下所有后缀为.json的文件 def jsonFiles = new File(jsonDirPath).listFiles({ file -> file.isFile() && file.name.toLowerCase().endsWith('.json') } as FileFilter) if (!jsonFiles) { println("指定目录下未找到JSON文件") return } jsonFiles.each { jsonFile -> mergeFile.append(jsonFile.getText()) } println("共处理${jsonFiles.size()}个文件,合并JSON已生成")
合法JSON格式合并补充说明
你原有逻辑是直接拼接文本,输出的内容不属于标准合法JSON格式,如果你需要输出可解析的标准JSON,可以根据你的文件结构选择对应处理方案:
- 场景1:每个待合并文件都是JSON数组,要合并为一个大数组
import groovy.json.JsonSlurper import groovy.json.JsonOutput def jsonSlurper = new JsonSlurper() def mergeResult = [] // 此处可替换为上面的手动路径列表或自动目录扫描结果 def fileLocations = ['/path/to/1.json', '/path/to/2.json', '/path/to/3.json'] fileLocations.each { filePath -> def json = jsonSlurper.parse(new File(filePath)) mergeResult.addAll(json) } new File('/path/to/merged.json').write(JsonOutput.toJson(mergeResult))
- 场景2:每个待合并文件都是JSON对象,要合并为一个大对象(重复key会被后加载的文件内容覆盖)
import groovy.json.JsonSlurper import groovy.json.JsonOutput def jsonSlurper = new JsonSlurper() def mergeResult = [:] def fileLocations = ['/path/to/1.json', '/path/to/2.json', '/path/to/3.json'] fileLocations.each { filePath -> def json = jsonSlurper.parse(new File(filePath)) mergeResult.putAll(json) } new File('/path/to/merged.json').write(JsonOutput.toJson(mergeResult))
内容的提问来源于stack exchange,提问作者johahi
相关产品推荐
相关产品推荐

