首頁  >  文章  >  後端開發  >  為什麼我的Go程式解析JSON錯誤?

為什麼我的Go程式解析JSON錯誤?

Susan Sarandon
Susan Sarandon原創
2024-11-15 12:39:03116瀏覽

Why Does My Go Program Parse JSON Incorrectly?

Parsing JSON into a Struct in Go

You want to parse a JSON file into a Go struct, but the program outputs incorrect values.

Issue

The struct elements are not exported, starting with lowercase letters. The JSON encoder/decoder ignores non-exported elements.

Solution

Export the struct elements by making the first letter uppercase:

type Settings struct {
    ServerMode bool `json:"serverMode"`
    SourceDir  string `json:"sourceDir"`
    TargetDir  string `json:"targetDir"`
}

json:"..." tags instruct the decoder to map JSON keys to struct elements.

Updated Code

var settings Settings

// ... (rest of the code)

Additional Notes

  • Check for errors when opening and parsing the JSON file.
  • Ensure the JSON file structure matches the struct definition.

以上是為什麼我的Go程式解析JSON錯誤?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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