gpt-3.5-turbo-0613· OpenAI
WildChat-4.8M (AI2)
read data from json file and unmarshal struct type in golang
- User
read data from json file and unmarshal struct type in golang
- Assistant
To read data from a JSON file and unmarshal it into a struct type in Go, you can follow these steps:
- Create a struct representing the JSON data. Ensure that the field names in the struct match the keys in the JSON file.
gotype Person struct { Name string `json:"name"` Age int `json:"age"` Email string `json:"email"` }- Open and read the JSON file.
gofile, err := os.Open("data.json") if err != nil { log.Fatal(err) } defer file.Close() byteValue, err := ioutil.ReadAll(file) if err != nil { log.Fatal(err) }- Unmarshal the JSON data into the struct.
govar person Person err = json.Unmarshal(byteValue, &person) if err != nil { log.Fatal(err) }- You can now access the values from the struct.