Go语言中如何提取JSON字符串的指定子集(仅保留data节点内排除appendix的内容并转为字符串)
Go语言中如何提取JSON字符串的指定子集(仅保留data节点内排除appendix的内容并转为字符串)
嘿,我完全get到你的需求了——从API返回的长串JSON里,只把data节点里的内容(还得去掉里面的appendix字段)抽出来,最后转成字符串对吧?我给你两种实用的处理方法,你可以根据自己的场景选:
方法一:结构体+RawMessage灵活处理
如果你的data结构大部分是固定的,只是要剔除appendix,可以用这种方法,既能保证类型安全,又不用提前定义data里的所有字段:
首先定义外层的结构体,用json.RawMessage暂存data的原始JSON内容,这样一开始不用解析data的内部细节:
import ( "encoding/json" "fmt" "net/http" ) // 外层API响应的结构体 type APIResponse struct { Data json.RawMessage `json:"data"` NeedsTrial bool `json:"needs_trial"` AdjustTime bool `json:"adjust_time"` Attempts int `json:"attempts"` }
然后按步骤处理:
- 发起请求拿到响应体
- 解析外层JSON到
APIResponse,把data的原始内容保留下来 - 把
data的原始内容解析成map(如果字段不固定)或者自定义结构体(如果字段固定) - 删除
appendix字段后重新序列化成字符串
示例代码:
func main() { resp, err := http.Get("你的API接口地址") if err != nil { panic(err) } defer resp.Body.Close() var apiResp APIResponse if err := json.NewDecoder(resp.Body).Decode(&apiResp); err != nil { panic(err) } // 把data解析成map,不用提前定义所有字段,更灵活 var dataMap map[string]interface{} if err := json.Unmarshal(apiResp.Data, &dataMap); err != nil { panic(err) } // 删除appendix字段,就算字段不存在也不会报错 delete(dataMap, "appendix") // 把处理后的data转成字符串 dataStr, err := json.Marshal(dataMap) if err != nil { panic(err) } fmt.Println(string(dataStr)) }
方法二:直接用嵌套Map一步到位
如果不想定义任何结构体,直接用嵌套map处理更省事,适合data字段不固定的场景:
func main() { resp, err := http.Get("你的API接口地址") if err != nil { panic(err) } defer resp.Body.Close() // 直接把整个JSON解析成嵌套map var fullRespMap map[string]interface{} if err := json.NewDecoder(resp.Body).Decode(&fullRespMap); err != nil { panic(err) } // 取出data部分的map,注意类型断言 dataMap, ok := fullRespMap["data"].(map[string]interface{}) if !ok { panic("JSON中data字段的格式不符合预期") } // 删除appendix字段 delete(dataMap, "appendix") // 转成字符串,如果需要格式化输出可以用json.MarshalIndent dataStr, err := json.Marshal(dataMap) if err != nil { panic(err) } fmt.Println(string(dataStr)) }
小提示:
- 如果
data里有嵌套的结构体,两种方法都能自动处理,map会解析成嵌套map - 要是你需要带缩进的格式化字符串,把
json.Marshal换成json.MarshalIndent(dataMap, "", " ")就行
备注:内容来源于stack exchange,提问作者unsafe_where_true
相关产品推荐
相关产品推荐

