Created
March 7, 2024 10:26
-
-
Save Integralist/ff0a0152fdb0cad90e392c19645bb5ac to your computer and use it in GitHub Desktop.
[Go convert JSON types when unmarshalling] #go #golang #json #unmarshal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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