首頁  >  文章  >  後端開發  >  如何在 Go 中將 JSON 檔案讀取為物件?

如何在 Go 中將 JSON 檔案讀取為物件?

Mary-Kate Olsen
Mary-Kate Olsen原創
2024-11-15 00:57:02274瀏覽

How Do You Read JSON Files as Objects in Go?

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:

  • Attempt 1:
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)".

  • Attempt 2:
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.

以上是如何在 Go 中將 JSON 檔案讀取為物件?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn