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

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

How to append to an interface{} in json file

问题

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

原始的json文件:

  1. {
  2. "frames": {
  3. "d_65541723636int": {
  4. "objectId": "d_65541723636"
  5. }
  6. }
  7. }

期望追加后的json文件:

  1. {
  2. "frames": {
  3. "d_65541723636int": {
  4. "objectId": "d_65541723636"
  5. },
  6. "anotherthing": {
  7. "objectId": "d_65541723636"
  8. }
  9. }
  10. }

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

英文:

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

Original json file:

  1. {
  2. "frames": {
  3. "d_65541723636int": {
  4. "objectId": "d_65541723636"
  5. }
  6. }
  7. }

expect json file after append:

  1. {
  2. "frames": {
  3. "d_65541723636int": {
  4. "objectId": "d_65541723636"
  5. }
  6. "anotherthing": {
  7. "objectId": "d_65541723636"
  8. }
  9. }
  10. }

How should I do it?

答案1

得分: 1

  1. import (
  2. "encoding/json"
  3. "fmt"
  4. )
  5. func main() {
  6. var m = make(map[string]interface{})
  7. sjson := `{
  8. "frames": {
  9. "d_65541723636int": {
  10. "objectId": "d_65541723636"
  11. }
  12. }
  13. }`
  14. json.Unmarshal([]byte(sjson), &m)
  15. m["anotherthing"] = make(map[string]interface{})
  16. m["anotherthing"].(map[string]interface{})["objectId"] = "d_65541723636"
  17. fmt.Printf("%v\n", m)
  18. }
  1. import (
  2. "encoding/json"
  3. "fmt"
  4. )
  5. func main() {
  6. var m = make(map[string]interface{})
  7. sjson := `{
  8. "frames": {
  9. "d_65541723636int": {
  10. "objectId": "d_65541723636"
  11. }
  12. }
  13. }`
  14. json.Unmarshal([]byte(sjson), &m)
  15. m["anotherthing"] = make(map[string]interface{})
  16. m["anotherthing"].(map[string]interface{})["objectId"] = "d_65541723636"
  17. fmt.Printf("%v\n", m)
  18. }
英文:
  1. import (
  2. "encoding/json"
  3. "fmt"
  4. )
  5. func main() {
  6. var m = make(map[string]interface{})
  7. sjson := `{
  8. "frames": {
  9. "d_65541723636int": {
  10. "objectId": "d_65541723636"
  11. }
  12. }
  13. }`
  14. json.Unmarshal([]byte(sjson), &m)
  15. m["anotherthing"] = make(map[string]interface{})
  16. m["anotherthing"].(map[string]interface{})["objectId"] = "d_65541723636"
  17. fmt.Printf("%v\n", m)
  18. }

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:

确定