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

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

在 golang 中解組 json 時如何跳過現有字段?

在 golang 中解組 json 時如何跳過現有字段?

Go
繁花如伊 2022-12-19 10:35:19
我使用jsonfile 來配置我的程序參數,并使用flagpackage 來配置相同的參數。當一些參數同時被json文件解析flag時,我希望使用通過flag.麻煩的是json文件路徑也是通過.解析出來的flag。調用后可以得到json路徑flag.parse(),但是參數也被解析了,那么Unmarshaljson會覆蓋flag解析的參數。示例 JSON:{    "opt1": 1,    "opt2": "hello"}示例代碼:var Config = struct {    Opt1 int    `json:"opt1"`    Opt2 string `json:"opt2"`}{    Opt1: 0,    Opt2: "none",}func main() {    // parse config file path    var configFile string    flag.StringVar(&configFile, "config", "", "config file path")    // parse options    flag.IntVar(&Config.Opt1, "opt1", Config.Opt1, "")    flag.StringVar(&Config.Opt2, "opt2", Config.Opt2, "")    // parse flags    flag.Parse()    // load config options from config.json file    if configFile != "" {        if data, err := ioutil.ReadFile(configFile); err != nil {            fmt.Printf("read config file error: %v\n", err)        } else if err = json.Unmarshal(data, &Config); err != nil {            fmt.Printf("parse config file error: %v\n", err)        }    }    fmt.Printf("%+v", Config)}程序示例輸出:./foo.exe -opt2 worldout:{Opt1:0 Opt2:world}./foo.exe -config config.json出去:{Opt1:1 Opt2:hello}./foo.exe -config config.json -opt2 world真正的出局:{Opt1:1 Opt2:hello}希望出局:{Opt1:1 Opt2:world}
查看完整描述

1 回答

?
汪汪一只貓

TA貢獻1898條經驗 獲得超8個贊

一個簡單的解決方案是首先解析 JSON 配置文件,完成后,再繼續解析 CLI 參數。


問題在于 JSON 配置文件也是 CLI arg。


flag.Parse()最簡單的解決方案是在解析配置文件后再次調用:


// load config options from config.json file

if configFile != "" {

    if data, err := ioutil.ReadFile(configFile); err != nil {

        fmt.Printf("read config file error: %v\n", err)

    } else if err = json.Unmarshal(data, &Config); err != nil {

        fmt.Printf("parse config file error: %v\n", err)

    }


    // parse flags again to have precedence

    flag.Parse()

}

第二個flag.Parse()將覆蓋并因此優先于來自 JSON 文件的數據。


加上這個,運行


./foo.exe -config config.json -opt2 world

輸出將是你想要的:


{Opt1:1 Opt2:world}


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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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