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 欧拉系统opt目录空间使用100%
  • ¥15 ul做导航栏格式不对怎么改?
  • ¥20 用户端如何上传图片到服务器和数据库里
  • ¥15 现在研究生在烦开题,看了一些文献,但不知道自己要做什么,求指导。
  • ¥30 vivado封装时总是显示缺少一个dcp文件
  • ¥100 pxe uefi启动 tinycore
  • ¥15 我pycharm运行jupyter时出现Jupyter server process exited with code 1,然后打开cmd显示如下
  • ¥15 可否使用carsim-simulink进行四轮独立转向汽车的联合仿真,实现四轮独立转向汽车原地旋转、斜向形式、横移等动作,如果可以的话在carsim中如何进行相应设置
  • ¥15 Caché 2016 在Java环境通过jdbc 执行sql报Parameter list mismatch错误,但是同样的sql使用连接工具可以查询出数据
  • ¥15 疾病的获得与年龄是否有关