Home > database >  How to append to an interface{} in json file
How to append to an interface{} in json file

Time:10-12

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?

CodePudding user response:

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