亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

我們如何使用 Go 編程語言讀取 JSON 文件?

我們如何使用 Go 編程語言讀取 JSON 文件?

Go
白板的微信 2023-06-12 16:16:01
我正在我的 Angular 應用程序上進行翻譯項目。我已經為此創建了所有不同的密鑰。我現在嘗試使用 Go 編程語言在我的翻譯中添加一些功能,以便快速工作。我嘗試用 Go 編程語言編寫一個函數,以便在命令行上讀取輸入用戶。我需要閱讀這個輸入文件才能知道里面是否缺少密鑰。此輸入用戶必須是 JSON 文件。我對這個函數有問題,在 處被阻止functions.Check(err),為了調試我的函數,我用 顯示了不同的變量fmt.Printf(variable to display)。readInput()我在我的主要功能中調用這個功能。函數readInput()如下:    // this function is used to read the user's input on the command linefunc readInput() string {    // we create a reader    reader := bufio.NewReader(os.Stdin)    // we read the user's input    answer, err := reader.ReadString('\n')    // we check if any errors have occured while reading    functions.Check(err)    // we trim the "\n" from the answer to only keep the string input by the user    answer = strings.Trim(answer, "\n")    return answer}在我的主要功能中,我調用readInput()了我創建的特定命令。此命令行可用于更新 JSON 文件并自動添加缺少的密鑰。我的func main是:      func main() {         if os.Args[1] == "update-json-from-json" {    fmt.Printf("please enter the name of the json file that will be used to     update the json file:")     jsonFile := readInput()    fmt.Printf("please enter the ISO code of the locale for which you want to update the json file: ")            // we read the user's input            locale := readInput()            // we launch the script            scripts.AddMissingKeysToJsonFromJson(jsonFile, locale)        }我可以給你我用于此代碼的命令行go run mis-t.go update-json-from-json請問我的代碼中缺少什么嗎?
查看完整描述

1 回答

?
開心每一天1111

TA貢獻1836條經驗 獲得超13個贊

假設該文件包含動態和未知的鍵和值,并且您無法在您的應用程序中對它們進行建模。然后你可以這樣做:



func main() {

    if os.Args[1] == "update-json-from-json" {

        ...

        jsonFile := readInput()


        var jsonKeys interface{}

        err := json.Unmarshal(jsonFile, &jsonKeys)

        functions.Check(err)



        ...

    }

}

將內容加載到 中empty interface,然后使用 go 反射庫 ( https://golang.org/pkg/reflect/ ) 遍歷字段,找到它們的名稱和值并根據您的需要更新它們。


另一種方法是 Unmarshal into a map[string]string,但這不能很好地處理嵌套的 JSON,而這可能(但我還沒有測試過)。


查看完整回答
反對 回復 2023-06-12
  • 1 回答
  • 0 關注
  • 163 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號