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

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

如何在 Go 中解組可以是數組或字符串的字段?

如何在 Go 中解組可以是數組或字符串的字段?

Go
慕運維8079593 2023-06-19 17:21:19
我正在嘗試解組此文件:{  "@babel/[email protected]": {    "licenses": "MIT",    "repository": "https://github.com/babel/babel/tree/master/packages/babel-code-frame",    "publisher": "Sebastian McKenzie",    "email": "[email protected]",    "path": "/Users/lislab/workspace/falcon-enrolment/frontend-customer/node_modules/@babel/code-frame",    "licenseFile": "/Users/lislab/workspace/falcon-enrolment/frontend-customer/node_modules/@babel/code-frame/LICENSE"  },  "[email protected]": {    "licenses": [      "AFLv2.1",      "BSD"    ],    "repository": "https://github.com/kriszyp/json-schema",    "publisher": "Kris Zyp",    "path": "/Users/lislab/workspace/falcon-enrolment/frontend-customer/node_modules/json-schema",    "licenseFile": "/Users/lislab/workspace/falcon-enrolment/frontend-customer/node_modules/json-schema/README.md"  }}進入這個結構:type Dependency struct {    Name    string    URL     string    Version string    License string}使用這些說明:dependencies := map[string]*json.RawMessage{}err = json.Unmarshal(file, &dependencies)// boilerplatefor key, value := range dependencies {    depVal := map[string]string{}    err = json.Unmarshal(*value, &depVal)    // boilerplate    result = append(result, depVal)}這個問題是在“[email protected]”中我們有一組許可證而不是一個字符串,因此我顯然得到了json: cannot unmarshal array into Go value of type string 有沒有辦法自動處理license可以是數組或字符串的字段?
查看完整描述

1 回答

?
慕田峪7331174

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

不幸的是,該軟件包沒有為此提供真正的自動解決方案json。


但是您可以將依賴項解組為 amap[string]*json.RawMessage而不是map[string]string. json.RawMessage只是一個[]byte,因此您可以根據第一個字節來決定消息的類型。


例子:


for _, value := range dependencies {

    depVal := map[string]*json.RawMessage{}


    _ = json.Unmarshal(*value, &depVal)


    // check if the first character of the RawMessage is a bracket

    if rune([]byte(*depVal["licenses"])[0]) == '[' {

        var licenses []string

        json.Unmarshal(*depVal["licenses"], &licenses)

        fmt.Println(licenses)

        // do something with the array

    }


    result = append(result, Dependency{

        URL:     string(*depVal["repository"]),

        License: string(*depVal["licenses"]),

    })

}

另一種解決方案是使用 2 個結構。一個包含字符串形式的依賴項,另一個包含數組形式的依賴項。然后您可以嘗試json.Unmarshal同時調用它們。例子:



type Dependency struct {

    Licenses string

    // other fields

}


type DependencyWithArr struct {

    Licenses []string

    // other fields

}


// in your function

for _, value := range dependencies {

    type1 := Dependency{}

    type2 := DependencyWithArr{}


    err = json.Unmarshal(*value, &type1)

    if err != nil {

        err = json.Unmarshal(*value, &type2)

        // use the array type

    } else {

        // use the single string type

    }

}


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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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