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

Groovy JSON处理:如何将点表示法转换为嵌套JSON结构?

Groovy实现JSON点表示法转嵌套结构

核心实现思路

通过递归函数处理每个键值对:拆分带点分隔的键,逐层构建嵌套Map;同时递归处理数组和嵌套Map类型的值,确保整个JSON结构的深度转换。

完整代码实现

import groovy.json.JsonSlurper
import groovy.json.JsonBuilder

def flattenToNested(Map input) {
    def result = [:]
    input.each { key, value ->
        if (key.contains('.')) {
            def parts = key.split('\\.', 2)
            def parentKey = parts[0]
            def childKey = parts[1]
            // 父键不存在则创建空Map,已存在则复用原有结构
            def nestedChild = flattenToNested([(childKey): value])
            result[parentKey] = (result[parentKey] ?: [:]) << nestedChild
        } else {
            // 递归处理数组或嵌套Map类型的值
            if (value instanceof List) {
                result[key] = value.collect { item ->
                    item instanceof Map ? flattenToNested(item) : item
                }
            } else if (value instanceof Map) {
                result[key] = flattenToNested(value)
            } else {
                result[key] = value
            }
        }
    }
    // 合并同父键的嵌套内容,避免覆盖
    return result.inject([:]) { acc, entry ->
        if (entry.value instanceof Map && acc.containsKey(entry.key)) {
            acc[entry.key] = acc[entry.key] << entry.value
        } else {
            acc[entry.key] = entry.value
        }
        acc
    }
}

// 测试输入(你的原始JSON)
def inputJson = '''[{
    "sender.senderContactInformation.senderContactPrefix": "Mr.",
    "sender.senderContactInformation.senderContactMiddleInitial": "man",
    "ord.ordToAddr1": "US",
    "dummy-target": "dummydefault",
    "sender.senderContactInformation.SenderContactType": "",
    "senderIdentifierName": "Abcxyz",
    "orderLineItems": [{
        "orderLineItemActionCode": "78",
        "OrderLineItemQuantity": "1",
        "patientID": "CKIO090",
        "defender.defenderContactInformation": "",
        "orderLineItemDetails": [{
            "orderLineItemDetailCode": "1",
            "ds1.dsType.dsName": ""
        }]
    }]
}]'''

// 解析JSON并执行转换
def slurper = new JsonSlurper()
def inputData = slurper.parseText(inputJson)
def outputData = inputData.collect { flattenToNested(it) }

// 输出格式化后的嵌套JSON
def builder = new JsonBuilder(outputData)
println builder.toPrettyString()

代码关键点说明

  1. 递归拆分键:将带点的键拆分为父键和子键,逐层构建嵌套Map,比如sender.senderContactInformation.senderContactPrefix会被拆分为sender -> senderContactInformation -> senderContactPrefix的三层结构。
  2. 数组与嵌套处理:自动识别数组和嵌套Map类型的值,递归调用转换函数,确保数组内部的对象也能完成点表示法转换。
  3. 同键合并:对同一父键下的多个子键进行合并,避免多次创建父键导致的结构覆盖问题。

执行上述代码后,输出结果将完全匹配你提供的期望嵌套JSON结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 03:32:36