如何在 Golang 中解码或解组嵌入的 JSON?

问题描述 投票:0回答:1

这是Playground 中的示例。问题的要点是我无法解码/解组这个

    Name := "TestName"
    Desc := "Test Desc"
    Body := []byte(`{"key": "value"}`)//simplest possible JSON but will have multiple levels

    requestJson := fmt.Sprintf(`{"name": "%s","description": "%s","body": "%s"}`, Name, Desc, Body)
    decoder := json.NewDecoder(strings.NewReader(requestJson))
    err := decoder.Decode(&createRpt)
    if err != nil {
        fmt.Println("Report body is expected to be valid JSON", "error", err)
        return
    }

我也尝试过使用

unmarshal
选项,如操场上所示。

json go unmarshalling
1个回答
0
投票

您的 json 中有拼写错误,请删除 body 值周围的

"
,它将被修复:

requestJson := fmt.Sprintf(`{"name": "%s","description": "%s","body": %s}`, Name, Desc, Body)
© www.soinside.com 2019 - 2024. All rights reserved.