lundi 23 décembre 2019

How to modify a nested field inside interface{}

I have an HTTP request body that is marshalled into an interface{} with encoding/json. The contents are JSON with unknown keys, but in some cases will be something that looks like:

{
  "person": {
     "name": "John",
     "age": 40
  },
  "location": {
    "city": "Chicago",
    "state": "IL"
  }
}

I want to write code that will interrogate the payload and if it matches the format, modify the name field.

I am trying to do something like this:

type Request struct {
  Payload interface{}
}

func (r *Request) ModifyName() {
  v := reflect.ValueOf(r.Payload)

  if v.Kind() == reflect.Map {
    for _, key := range v.MapKeys() {
      if key.String() == "person" {
        person := v.MapIndex(key)
        name := person.FieldByName("name")
        if name.IsValid() {
          name.SetString("Bob")
        }
      }
    }
  }
}

The error I get is: reflect: call of reflect.Value.FieldByName on interface Value

I understand that I can only call FieldByName on struct Value, but I don't understand how to achieve my goal.





Aucun commentaire:

Enregistrer un commentaire