如何向 JSON 文件中的 interface{} 追加内容?

huangapple go评论70阅读模式
英文:

How to append to an interface{} in json file

问题

我正在尝试将一个map[string]interface{}追加到一个现有的map[string]interface{}中的json文件中。

原始的json文件:

{
    "frames": {
        "d_65541723636int": {
            "objectId": "d_65541723636"
        }
    }
}

期望追加后的json文件:

{
    "frames": {
        "d_65541723636int": {
            "objectId": "d_65541723636"
        },
        "anotherthing": {
            "objectId": "d_65541723636"
        }
    }
}

我应该如何实现这个功能?

英文:

I'm trying to append a map[string]interface{} to an existing map[string]interface{} in a json file.

Original json file:

{
   
    "frames": {
      "d_65541723636int": {
        "objectId": "d_65541723636"
      }
    }
 }

expect json file after append:

{
       
 "frames": {
    "d_65541723636int": {
        "objectId": "d_65541723636"
    }
    "anotherthing": {
        "objectId": "d_65541723636"
    }
 }
}

How should I do it?

答案1

得分: 1

import (
	"encoding/json"
	"fmt"
)

func main() {
	var m = make(map[string]interface{})
	sjson := `{
		"frames": {
			"d_65541723636int": {
				"objectId": "d_65541723636"
			}
		}
	}`
	json.Unmarshal([]byte(sjson), &m)
	m["anotherthing"] = make(map[string]interface{})
	m["anotherthing"].(map[string]interface{})["objectId"] = "d_65541723636"
	fmt.Printf("%v\n", m)
}
import (
	"encoding/json"
	"fmt"
)

func main() {
	var m = make(map[string]interface{})
	sjson := `{
		"frames": {
			"d_65541723636int": {
				"objectId": "d_65541723636"
			}
		}
	}`
	json.Unmarshal([]byte(sjson), &m)
	m["anotherthing"] = make(map[string]interface{})
	m["anotherthing"].(map[string]interface{})["objectId"] = "d_65541723636"
	fmt.Printf("%v\n", m)
}
英文:
import (
	"encoding/json"
	"fmt"
)

func main() {
	var m = make(map[string]interface{})
	sjson := `{   
    "frames": {
      "d_65541723636int": {
        "objectId": "d_65541723636"
      }
    }
 }`
	json.Unmarshal([]byte(sjson), &m)
	m["anotherthing"] = make(map[string]interface{})
	m["anotherthing"].(map[string]interface{})["objectId"] = "d_65541723636"
	fmt.Printf("%v\n", m)
}

huangapple
  • 本文由 发表于 2022年10月12日 11:55:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/74036325.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定