当前位置: > > > > 如何访问该结构中的某些值
如何访问该结构中的某些值
来源:stackoverflow
2024-04-20 14:39:35
0浏览
收藏
本篇文章主要是结合我之前面试的各种经历和实战开发中遇到的问题解决经验整理的,希望这篇《如何访问该结构中的某些值》对你有很大帮助!欢迎收藏,分享给更多的需要的朋友学习~
问题内容
我正在 go 中记录一些内容。这是值,下面是我记录 reflect.typeof(attributes.pdp.sellableunits[i].attributes) 时的结果:
[{22555278 val 03.5}]
[{22554867 val 04.0}]
[{22555002 val 04.5}]
[{22555279 val 05.0}]
[{22555280 val 05.5}]
[{22555144 val 06.0}]
[{22555145 val 06.5}]
[{22555146 val 07.0}]
// typeof
[1]struct { id string "json:\"id\""; type string "json:\"type\""; value string "json:\"value\"" }
[1]struct { id string "json:\"id\""; type string "json:\"type\""; value string "json:\"value\"" }
[1]struct { id string "json:\"id\""; type string "json:\"type\""; value string "json:\"value\"" }
[1]struct { id string "json:\"id\""; type string "json:\"type\""; value string "json:\"value\"" }
[1]struct { id string "json:\"id\""; type string "json:\"type\""; value string "json:\"value\"" }
[1]struct { id string "json:\"id\""; type string "json:\"type\""; value string "json:\"value\"" }
[1]struct { id string "json:\"id\""; type string "json:\"type\""; value string "json:\"value\"" }
[1]struct { id string "json:\"id\""; type string "json:\"type\""; value string "json:\"value\"" }
我希望能够仅记录 id 字符串,在本例中是代码块顶部的许多数字字符串(22555278、22554867、22555002 等…)
这是我的代码来记录所有这些
// Struct
type sizeJ struct {
Pdp struct {
Units []struct {
Attributes [1]struct {
ID string `json:"id"`
Type string `json:"type"`
Value string `json:"value"`
} `json:"attributes"`
} `json:"Units"`
} `json:"pdp"`
}
// ...
body, _ := ioutil.ReadAll(resp.Body)
xml := strings.NewReader(string(body))
j, _ := xj.Convert(xml)
if err != nil {
log.Fatal(err)
}
var attributes sizeJ
json.Unmarshal([]byte(j.String()), &attributes)
for i := 0; i < len(attributes.Pdp.Units); i++ {
fmt.Println(reflect.TypeOf(attributes.Pdp.Units[i].Attributes))
}
解决方案
您的类型声明为:
type sizej struct {
pdp struct {
units []struct {
attributes [1]struct {
id string `json:"id"`
type string `json:"type"`
value string `json:"value"`
} `json:"attributes"`
} `json:"units"`
} `json:"pdp"`
}
您可以只打印 id:
for i := 0; i < len(attributes.Pdp.Units); i++ {
// fmt.Println(reflect.TypeOf(attributes.Pdp.Units[i].Attributes))
fmt.Printf("ID: %s\n", attributes.Pdp.Units[i].Attributes[0].ID)
}
本篇关于《如何访问该结构中的某些值》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注米云公众号!
