Reading JSON Files as Object in Go
In Go, you can encounter difficulties when attempting to read a JSON file and parse it as a JSON object.
Failed Attempts
Some failed attempts to read JSON files as objects include:
plan, _ := ioutil.ReadFile(filename) // filename is the JSON file to read var data interface{} err := json.Unmarshal(plan, data)
This results in the error "json: Unmarshal(nil)".
generatePlan, _ := json.MarshalIndent(plan, "", " ") // plan is a pointer to a struct
This produces a string output, but casting it to a string makes it impossible to loop through as a JSON object.
Solution
The key to resolving this issue lies in the value pointed to by json.Unmarshal. It must be a pointer.
plan, _ := ioutil.ReadFile(filename) var data interface{} err := json.Unmarshal(plan, &data)
Type Assertion
When using an empty interface in unmarshal, you need to use type assertion to get underlying values as native Go types:
bool, for JSON booleans float64, for JSON numbers string, for JSON strings []interface{}, for JSON arrays map[string]interface{}, for JSON objects nil for JSON null
Best Practice
It's highly recommended to use a concrete structure to populate JSON data using Unmarshal. This provides better clarity and avoids the need for type assertions.
The above is the detailed content of How Do You Read JSON Files as Objects in Go?. For more information, please follow other related articles on the PHP Chinese website!