Skip to content

Instantly share code, notes, and snippets.

@Integralist
Created March 7, 2024 10:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Integralist/ff0a0152fdb0cad90e392c19645bb5ac to your computer and use it in GitHub Desktop.
Save Integralist/ff0a0152fdb0cad90e392c19645bb5ac to your computer and use it in GitHub Desktop.
[Go convert JSON types when unmarshalling] #go #golang #json #unmarshal
package main
import (
"encoding/json"
"fmt"
)
func main() {
var jsonBlob = []byte(`[
{"str": "Foo", "num": "1", "bool": "true", "its": 3},
{"str": "Bar", "num": "2", "bool": "false", "its": 4}
]`)
type Thing struct {
String string `json:"str"`
Number int `json:"num,string"`
Boolean bool `json:"bool,string"`
// IntToString string `json:"its,int"` // error: json: cannot unmarshal number into Go struct field Thing.its of type string
}
var things []Thing
err := json.Unmarshal(jsonBlob, &things)
if err != nil {
fmt.Println("error:", err)
}
fmt.Printf("%#v", things)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment