douqihou7537 2018-02-02 20:39
浏览 230
已采纳

Golang合并JSON

Here's an example of what I need:

Default JSON:

{
    "name": "John",
    "greetings": {
        "first": "hi",
        "second": "hello"
    }
}

merged with the changes:

{
    "name": "Jane",
    "greetings": {
        "first": "hey"
    }
}

should become:

{
    "name": "Jane",
    "greetings": {
        "first": "hey",
        "second": "hello"
    }
}

Here's what I've tried:

package main

import (
    "encoding/json"
    "fmt"
    "reflect"
)

func MergeJSON(defaultJSON, changedJSON string) string {
    var defaultJSONDecoded map[string]interface{}
    defaultJSONUnmarshalErr := json.Unmarshal([]byte(defaultJSON), &defaultJSONDecoded)
    if defaultJSONUnmarshalErr != nil {
        panic("Error unmarshalling first JSON")
    }
    var changedJSONDecoded map[string]interface{}
    changedJSONUnmarshalErr := json.Unmarshal([]byte(changedJSON), &changedJSONDecoded)
    if changedJSONUnmarshalErr != nil {
        panic("Error unmarshalling second JSON")
    }
    for key, _ := range defaultJSONDecoded {
        checkKeyBeforeMerging(key, defaultJSONDecoded[key], changedJSONDecoded[key], changedJSONDecoded)
    }
    mergedJSON, mergedJSONErr := json.Marshal(changedJSONDecoded)
    if mergedJSONErr != nil {
        panic("Error marshalling merging JSON")
    }
    return string(mergedJSON)
}

func checkKeyBeforeMerging(key string, defaultMap interface{}, changedMap interface{}, finalMap map[string]interface{}) {
    if !reflect.DeepEqual(defaultMap, changedMap) {
        switch defaultMap.(type) {
        case map[string]interface{}:
            //Check that the changed map value doesn't contain this map at all and is nil
            if changedMap == nil {
                finalMap[key] = defaultMap
            } else if _, ok := changedMap.(map[string]interface{}); ok { //Check that the changed map value is also a map[string]interface
                defaultMapRef := defaultMap.(map[string]interface{})
                changedMapRef := changedMap.(map[string]interface{})
                for newKey, _ := range defaultMapRef {
                    checkKeyBeforeMerging(newKey, defaultMapRef[newKey], changedMapRef[newKey], finalMap)
                }
            }
        default:
            //Check if the value was set, otherwise set it
            if changedMap == nil {
                finalMap[key] = defaultMap
            }
        }
    }
}

func main() {
    defaultJSON := `{"name":"John","greetings":{"first":"hi","second":"hello"}}`
    changedJSON := `{"name":"Jane","greetings":{"first":"hey"}}`
    mergedJSON := MergeJSON(defaultJSON, changedJSON)
    fmt.Println(mergedJSON)
}

The code above returns the following:

{
    "greetings": {
        "first": "hey"
    },
    "name": "Jane",
    "second": "hello"
}

So basically any changes should be applied to the default and return the full JSON. I also need this to work recursively.

How can I fix this? I can see where I went wrong, I'm just not sure how to make it work recursively.

Thanks

  • 写回答

1条回答 默认 最新

  • doushi9780 2018-02-02 21:12
    关注

    Your issue in the posted code is with your recursive call:

    checkKeyBeforeMerging(newKey, defaultMapRef[newKey], changedMapRef[newKey], finalMap)
    

    The reference to finalMap should actually be the nested part of the merged map. Meaning replace finalMap with something like finalMap[key].(map[string]interface{}).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求帮我调试一下freefem代码
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图