0

Considering I have the following struct

type Product struct {
    Price int `json:"price" bson:"price"`
}

However, when I query an external API, the JSON comes in as a String.

[{ "price": "10000"}, { "price": "100"} ]

If i use json.Unmarshal it will fail because my struct is integer while the JSON is a string.

I set the price as integer because I need to store it in mongodb as integer.

Any solution to this mismatch type issues?

Someone Special
  • 12,479
  • 7
  • 45
  • 76
  • Implement separate structure with int price to save into DB. Convert Product to that struct by assigning every field. – Dmitry Harnitski Jun 19 '22 at 19:22
  • 2
    End up i have to use 2 separate structs. One struct with the above suggested answer using `json:",string"` to insert into database, then one without the json line for querying database, so it will be sent to client in **int** instead of **string** when json encoded. – Someone Special Jun 19 '22 at 20:18

0 Answers0