json - 从 groovy 合并两个 JSON
问题描述
我有 2 个 JSON 文件,我想合并这 2 个文件并使用 groovy 创建一个 JSON 消息。基于“类型”值,我将合并这两个 JSON 文件。
- 如果 JSON 消息 1 的 JSON 对象的给定“类型”在 JSON 消息 2 中不存在,则相关 JSON 对象应包含在输出 JSON 消息中。
- JSON message2 中的所有 JSON 对象都应包含在输出 JSON 消息中
- 预期的样本格式如下所示
输入 JSON 消息1
{"message":[{"name":"HelloFile","type": "input"},{"name":"SecondFile","type": "error"}]
输入 JSON 消息2
[{"name":"NewFile","type": "input"},{"name":"MyFile","type": "output"}]
预期的 JSON
{"message":[{"name":"NewFile","type": "input"},{"name":"MyFile","type": "output"},{"name":"SecondFile","type": "error"}]}
我使用了下面的常规代码。
JsonBuilder jsonBuilder = new JsonBuilder(JSON1)
jsonBuilder.content.message= JSON2
def updatedBody = jsonBuilder.toString()
从上面的代码中,我得到了以下消息。
{"message":[{"name":"NewFile","type": "input"},{"name":"MyFile","type": "output"}]}
对此进行排序的任何帮助将不胜感激。
解决方案
尝试使用 JsonSlurper:
import groovy.json.*
def json1 = '{"message":[{"name":"HelloFile","type": "input"},{"name":"SecondFile","type": "error"}]}'
def json2 = '[{"name":"NewFile","type": "input"},{"name":"MyFile","type": "output"}]'
def slurper = new JsonSlurper()
def json1Obj = slurper.parseText(json1)
def json2Obj = slurper.parseText(json2)
json1Obj.message+=json2Obj
println JsonOutput.toJson(json1Obj)
这打印:
{"message":[{"name":"HelloFile","type":"input"},{"name":"SecondFile","type":"error"},{"name":"NewFile","type":"input"},{"name":"MyFile","type":"output"}]}
推荐阅读
- oop - 为了不破坏 SRP,您是否在单独的类中定义应用程序的每个业务逻辑功能?
- excel - 如何在 VBA 中打开长路径文件?
- android - [FLUTTER]:PersistentBottomNavBar 包有问题
- ios - 放大手势和旋转手势 SwiftUI
- laravel-6 - Laravel 6. 语法错误,意外 ')',期待 '['
- azure - 无法从 AKS 中的 pod ping 任何外部 IP
- node.js - 如何从 node.js 中的 AWS Lambda 函数制作 mongodump?
- json - JQ,将CSV(父子格式)转换为JSON,另一个问题
- windows - CMake 在 Windows 上搜索 CUDA 编译器时使用的路径太长
- vue.js - vue-i18n 不使用 vuetify 组件字符串