1

is there a way to set field tag of a struct ? for example :

type contact struct {
    Mail string `json:"contact"`
}

newStruct := setTag(temp, "Mail", "mail")

data, _ := json.Marshaller(qwe)
fmt.Println(data)

and it accepts this payload:

{
    "mail": "blabla"
}
CallMeLoki
  • 1,162
  • 9
  • 19
  • Possible duplicate of [What is the correct JSON content type?](http://stackoverflow.com/questions/477816/what-is-the-correct-json-content-type) – CallMeLoki Dec 11 '16 at 17:02

2 Answers2

3

Looks like you want your key of the json to be a variable. You can do this by using the map data type.

package main

import "fmt"
import "encoding/json"

func main() {
    asd := "mail"
    qwe := make(map[string]string)

    qwe[asd] = "jack"

    data, _ := json.Marshal(qwe)
    fmt.Println(string(data))  // Prints "{mail: jack}"
}

playground

Aruna Herath
  • 4,965
  • 1
  • 34
  • 51
0

You have to export the key. Working example

From godoc for package json.Marshal,

Struct values encode as JSON objects. Each exported struct field becomes a member of the object unless

  • the field's tag is "-", or
  • the field is empty and its tag specifies the "omitempty" option.
Community
  • 1
  • 1
Fallen
  • 4,256
  • 1
  • 24
  • 43