Home >Backend Development >Golang >How to Properly Read and Parse JSON Files in Go?
Reading JSON Files as JSON Objects in Go
While attempting to read a JSON file into a variable, subsequent attempts to loop through it and retrieve JSON object values can lead to problematic outcomes. The initial attempt using the Marshal command yields numeric output, while a subsequent attempt to store JSON values in a struct and use MarshalIndent results in a string output.
For success, an interface value being populated by json.Unmarshal must be a pointer. The correct approach is as follows:
plan, _ := ioutil.ReadFile(filename) var data interface{} err := json.Unmarshal(plan, &data)
The error "Unmarshal(nil)" observed in the initial attempt indicates a problem with file reading. Checking the error returned by ioutil.ReadFile is crucial.
Furthermore, using an empty interface in unmarshal requires type assertion to access underlying values as Go primitive types. A superior approach involves defining a concrete structure for use with json.Unmarshal.
The above is the detailed content of How to Properly Read and Parse JSON Files in Go?. For more information, please follow other related articles on the PHP Chinese website!