type Params struct {
MyNum string `json:"req_num"`
}
So I need to assign the value of MyNum
to another variable given a "req_num
" string key for some functionality I'm writing in the beego
framework. Is this possible in Go
and if so how?
I looked at the reflect library and couldn't find a way.
Here is an example of what I am trying to do. params is a variable of type Params with the value of MyNum initialized to "123" let's say. f currently does not get "123". It says "" when I log it to the console.
b := "req_num"
r := reflect.ValueOf(params)
f := reflect.Indirect(r).FieldByName(b)
EDIT: I will be doing this for multiple params (above I set b to an example field value "req_num") and I want to write it so I don't have to know the name of the field stored in b.
Loop through the fields in the type looking for a field with given JSON tag name. The value is in the corresponding field of the value.
name := "req_num"
v := reflect.ValueOf(Params{MyNum: "Hello"})
t := v.Type()
for i := 0; i < t.NumField(); i++ {
if strings.Split(t.Field(i).Tag.Get("json"), ",")[0] == name {
fmt.Printf("the value is %q
", v.Field(i).Interface().(string))
}
}
Use the JSON codec to do the work:
p, _ := json.Marshal(Params{MyNum: "123"}) // encode to JSON
var m map[string]interface{}
json.Unmarshal(p, &m) // decode to map
fmt.Println(m["req_num"]) // get value from the map
Runnable example in the Go Playground
You can avoid allocating the entire JSON document in memory by piping an encoder to a decoder:
value := Params{MyNum: "123"}
r, w := io.Pipe()
go func() {
json.NewEncoder(w).Encode(value)
w.Close()
}()
var m map[string]interface{}
json.NewDecoder(r).Decode(&m)
fmt.Println(m["req_num"])