登录
首页 >  Golang >  Go问答

将嵌套 JSON 提取为字符串

来源:stackoverflow

时间:2024-03-29 18:15:37 395浏览 收藏

IT行业相对于一般传统行业,发展更新速度更快,一旦停止了学习,很快就会被行业所淘汰。所以我们需要踏踏实实的不断学习,精进自己的技术,尤其是初学者。今天golang学习网给大家整理了《将嵌套 JSON 提取为字符串》,聊聊,我们一起来看看吧!

问题内容

我有一个 json 对象,我可以成功地将其转换为 go 结构。但是,我有一个要求,需要将 json 中的嵌套对象解析为字符串,但我无法做到这一点。

这是有效的代码。

有效的简单 json

{
    "timestamp": "1232159332",
    "duration": 0.5,
}

它转换为以下结构

type beat struct {
    timestamp   string      `json:"timestamp"`
    duration    float32     `json:"duration"`
}

func addbeat(w http.responsewriter,  r *http.request) {
    
    // step 1 get json parameters:
    b := beat {}

    decoder := json.newdecoder(r.body)
    err := decoder.decode(&b)
    checkerr(err)

    fmt.println("beat: ", b)
}

在以下 json 中,嵌套的 data 对象是动态填充的,其结构可能会有所不同。这就是为什么我需要将其提取为字符串并将其存储在数据库中,但 go 不会将其提取为字符串。 这不起作用

{
    "timestamp": "1232159332",
    "duration": 0.5,
    "data": {
       "key1": "val1",
       "key2": "val2"
    } 
}

go 代码(不起作用)

type beat struct {
    timestamp   string      `json:"timestamp"`
    duration    float32     `json:"duration"`
    data        string      `json:"data"`
}

func addbeat(w http.responsewriter,  r *http.request) {
    
    // step 1 get json parameters:
    b := beat {}

    decoder := json.newdecoder(r.body)
    err := decoder.decode(&b)
    checkerr(err)

    fmt.println("beat: ", b)
}

这是我得到的错误

2020/11/25 10:45:24 http: panic serving [::1]:50082: json: cannot unmarshal object into Go struct field Beat.data of type string

现在的问题是,在这种情况下,如何将嵌套对象 data 提取并解码为 go 中的字符串?


解决方案


您可能需要使用 json.rawmessage

type beat struct {
    timestamp   string      `json:"timestamp"`
    duration    float32     `json:"duration"`
    data        json.rawmessage      `json:"data"`
}

data := []byte(`{
    "timestamp": "1232159332",
    "duration": 0.5,
    "data": {
       "key1": "val1",
       "key2": "val2"
    } 
}`)
b := beat{}
err := json.unmarshal(data, &b)
if err != nil {
    panic(err)
}
fmt.println(string(b.data))

https://play.golang.org/p/tHe4kBMSEEJ

或者实现 unmarshaller 接口:

https://play.golang.org/p/p50GW57yH_U

type Beat struct {
    Timestamp   string      `json:"timestamp"`
    Duration    float32     `json:"duration"`
    Data        string      `json:"data"`
}

func (b *Beat) UnmarshalJSON(data []byte) error {
    type beat struct {
        Timestamp   string          `json:"timestamp"`
        Duration    float32         `json:"duration"`
        Data        json.RawMessage `json:"data"`
    }
    bb := &beat{}
    err := json.Unmarshal(data, bb)
    if err != nil {
        return err
    }
    b.Timestamp = bb.Timestamp
    b.Duration = bb.Duration
    b.Data = string(bb.Data)
    return nil
}

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>