1 回答

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
}
}
- 1 回答
- 0 關注
- 138 瀏覽
添加回答
舉報