Go语言如何从大型JSON结构中提取指定textValue字段数据
解决方案
步骤1:修正JSON语法问题
你提供的原始JSON存在语法错误,author字段缺少闭合大括号,修正后的合法JSON如下:
{ "id": 759, "author": { "id": 1, "name": "Gogi Na Vole" }, "completedOn": "Never", "custom_fields": [ { "id": 86, "name": "property_86", "label": "Type of Question", "value": [ "90" ], "textValue": [ "Other" ] }, { "id": 69, "name": "property_69", "label": "Client", "value": [ "82" ], "textValue": [ "BigFoot Inc." ] } ] }
步骤2:补全结构体定义
根据JSON结构定义对应Go结构体,添加json标签完成字段映射:
// CustomField 对应custom_fields数组的单个元素结构 type CustomField struct { ID int `json:"id"` Name string `json:"name"` Label string `json:"label"` Value []string `json:"value"` TextValue []string `json:"textValue"` } // TicketData 对应JSON根结构 type TicketData struct { ID int `json:"id"` Author map[string]interface{} `json:"author"` // 无需解析author内容时可直接用空接口 CompletedOn string `json:"completedOn"` CustomFields []CustomField `json:"custom_fields"` }
步骤3:添加筛选逻辑
遍历CustomFields数组时添加判断条件,即可提取目标字段:
func main() { var data TicketData jsonErr := json.Unmarshal(body, &data) if jsonErr != nil { fmt.Println("JSON解析错误:", jsonErr) return } // 方式1:按textValue值直接匹配 for _, field := range data.CustomFields { if len(field.TextValue) > 0 && field.TextValue[0] == "BigFoot Inc." { fmt.Printf("匹配到目标textValue:%#v\n", field.TextValue) } } // 方式2:更通用的方案,按label筛选客户字段再取值,避免硬编码公司名 for _, field := range data.CustomFields { if field.Label == "Client" { fmt.Printf("客户名称textValue:%#v\n", field.TextValue) break } } }
完整可运行代码
package main import ( "encoding/json" "fmt" ) var body = []byte(` { "id": 759, "author": { "id": 1, "name": "Gogi Na Vole" }, "completedOn": "Never", "custom_fields": [ { "id": 86, "name": "property_86", "label": "Type of Question", "value": [ "90" ], "textValue": [ "Other" ] }, { "id": 69, "name": "property_69", "label": "Client", "value": [ "82" ], "textValue": [ "BigFoot Inc." ] } ] } `) type CustomField struct { ID int `json:"id"` Name string `json:"name"` Label string `json:"label"` Value []string `json:"value"` TextValue []string `json:"textValue"` } type TicketData struct { ID int `json:"id"` Author map[string]interface{} `json:"author"` CompletedOn string `json:"completedOn"` CustomFields []CustomField `json:"custom_fields"` } func main() { var data TicketData jsonErr := json.Unmarshal(body, &data) if jsonErr != nil { fmt.Println("JSON解析失败:", jsonErr) return } for _, field := range data.CustomFields { if field.Label == "Client" { fmt.Printf("提取到目标textValue:%#v\n", field.TextValue) break } } }
运行输出结果:
提取到目标textValue:[]string{"BigFoot Inc."}
内容的提问来源于stack exchange,提问作者Glawk
相关产品推荐
相关产品推荐

