gpt4 book ai didi

json - 递归地合并 JSON 对象

转载 作者:IT王子 更新时间:2023-10-29 02:10:17 29 4
gpt4 key购买 nike

这是我需要的示例:

默认 JSON:

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

与更改合并:

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

应该变成:

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

这是我尝试过的:

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)
}

上面的代码返回以下内容:

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

所以基本上任何更改都应该应用到默认值并返回完整的 JSON。我还需要它来递归工作。

我该如何解决这个问题?我可以看到我哪里出错了,我只是不确定如何使其递归工作。

谢谢

最佳答案

您在发布的代码中遇到的问题与您的递归调用有关:

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

finalMap 的引用实际上应该是合并映射的嵌套部分。意思是将 finalMap 替换为类似 finalMap[key].(map[string]interface{}) 的内容。

关于json - 递归地合并 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48590555/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com