You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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"`
}

然后按步骤处理:

  1. 发起请求拿到响应体
  2. 解析外层JSON到APIResponse,把data的原始内容保留下来
  3. 把data的原始内容解析成map(如果字段不固定)或者自定义结构体(如果字段固定)
  4. 删除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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.13 16:28:21