Miljan Rakita
Miljan Rakita

Reputation: 1533

golang set new value to object with type map[string]interface{}

I got json str which i parse like this.

var bdoc interface{}
bson.UnmarshalJSON([]byte(gjson.Get(*str, "user").String()), &bdoc)

my bdoc is of type map[string]interface{}. When i want to get key from my map i do it like this:

bdoc.(map[string]interface{})["pk"]

But how can i set a new value for that "pk" key ? I want to convert that bdoc["pk"] = "1234567". The new value will not be of type interface but of type string.

Upvotes: 4

Views: 6531

Answers (1)

Adrian
Adrian

Reputation: 2113

You can set string and value stay as string type

package main

import (
    "fmt"
    "log"
)

func main() {

    var bdoc interface{}
    aMap, ok := bdoc.(map[string]interface{})
    if !ok {
       log.Fatalf("Failed to cast %T", bdoc)
    }
    //depending on JSON settting pk number may have json.Numbe or float64
    fmt.Prinf("%v  %T\n", aMap["pk"], aMap["pk"])
   aMap["pk"] ="1234"
    fmt.Prinf("%v  %T\n", aMap["pk"], aMap["pk"])

}

Upvotes: 2

Related Questions