2

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"
}
1

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.