title: How do I dynamically change the struct's json tag?
body: <p>I have the following:</p>
  
  <pre><code>package main
  
  import (
      "encoding/json"
      "fmt"
      "os"
      "reflect"
  )
  
  type User struct {
      ID   int64  `json:"id"`
      Name string `json:"first"` // want to change this to `json:"name"`
      tag  string `json:"-"`
      Another
  }
  
  type Another struct {
      Address string `json:"address"`
  }
  
  func (u *User) MarshalJSON() ([]byte, error) {
      value := reflect.ValueOf(*u)
      for i := 0; i &lt; value.NumField(); i++ {
          tag := value.Type().Field(i).Tag.Get("json")
          field := value.Field(i)
          fmt.Println(tag, field)
      }
      return json.Marshal(u)
  }
  
  func main() {
          anoth := Another{"123 Jennings Street"}
      _ = json.NewEncoder(os.Stdout).Encode(
          &amp;User{1, "Ken Jennings", "name",
               anoth},
      )
  }
  </code></pre>
  
  <p>I am trying to json encode the struct but before I do I need to change the json key...eg the final json should look like:</p>
  
  <pre><code>{"id": 1, "name": "Ken Jennings", "address": "123 Jennings Street"}
  </code></pre>
  
  <p>I noticed the method for value.Type().Field(i).Tag.Get("json"), however there is no setter method. Why? and how do I get the desired json output.</p>
  
  <p>Also, how do I iterate through all the fields, including the embedded struct Another?</p>
  
  <p><a href="https://play.golang.org/p/Qi8Jq_4W0t" rel="noreferrer">https://play.golang.org/p/Qi8Jq_4W0t</a></p>