Reading JSON Files as JSON Objects in Go
To read a JSON file as a JSON object in Go, it's crucial to understand the concept of pointers and type assertion.
Reading the JSON File
plan, err := ioutil.ReadFile(filename) if err != nil { log.Fatal(err) }
Unmarshaling the Data
To store the JSON object, you'll need a pointer to a variable, as specified in the Go documentation:
var data interface{} if err := json.Unmarshal(plan, &data); err != nil { log.Fatal(err) }
This stores the JSON object in the memory location pointed to by data.
Accessing the JSON Object
Since data is an interface, you must use type assertion to access its underlying values:
switch data := data.(type) { case map[string]interface{}: // Loop through the map as a JSON object for key, value := range data { fmt.Println(key, value) } case []interface{}: // Loop through the slice as a JSON array for _, value := range data { fmt.Println(value) } default: // Handle other types as needed }
Marshaling for Debugging
If you need to view the JSON object as a string for debugging purposes, you can use:
jsonString, err := json.Marshal(data) if err != nil { log.Fatal(err) } fmt.Println(string(jsonString))
Note:
The above is the detailed content of How to Read JSON Files as JSON Objects in Go?. For more information, please follow other related articles on the PHP Chinese website!