Struct field with reserved name golang
Asked Answered
O

2

26

Hi Im doing an API client and I want to use a struct to pull out the json, the problem is that one of the json fields should be named type, as far as I know it is a reserved keyword, how can I create a struct with a "type" field in it?

Example:

What I want to do:

type Card struct {
  cardId  string
  name    string
  cardSet string
  type    string
}
Organism answered 27/8, 2015 at 20:34 Comment(1)
Read the package documentation (preferably before asking questions). It'll tell you two important things, a) you need to export your fields and b) you can use a struct tag to rename the fields to/from JSON.Lavonnelaw
H
35

That won't work because you're not exporting the field names. To use different field names in the JSON output, you can use struct tags. For example, to name the fields CardID, Name, CardSet, and Type in the JSON output, you can define your struct like this:

type Card struct {
    CardID  string `json:"cardId"`
    Name    string `json:"name"`
    CardSet string `json:"cardSet"`
    Type    string `json:"type"`
}

The json:"<name>" tags specify the field names to use in the JSON output.

Hemmer answered 27/8, 2015 at 20:38 Comment(0)
D
5

You have to use json annotations on your model. Also, the fields have to be exported (upper case) or the unmarshaller won't be able to make use of them.

type Card struct {
  CardId  string `json:"cardId"`
  Name    string `json:"name"`
  CardSet string `json:"cardSet"`
  TheType    string  `json:"type"`
}
Democratize answered 27/8, 2015 at 20:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.