如何在Golang中解码或解组嵌入的JSON?[已关闭]

hec6srdp  于 12个月前  发布在  Go
关注(0)|答案(2)|浏览(70)

已关闭此问题为not reproducible or was caused by typos。它目前不接受回答。

此问题是由打印错误或无法再重现的问题引起的。虽然类似的问题可能是on-topic在这里,这一个是解决的方式不太可能帮助未来的读者。
14天前关闭
Improve this question
这是sample in the 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选项,可以在操场上看到。

brccelvz

brccelvz1#

你应该不惜一切代价避免像这样格式化你自己的JSON。只需创建一个可以正确封送的结构:

type Foo struct {
    Name        string          `json:"name"`
    Description string          `json:"description"`
    Body        json.RawMessage `json:"body"`
}

func main() {
    name, desc := "Test Name", "Test description, lorum ipsum"
    body := []byte(`{"key": "value"}`)
    jData, err := json.Marshal(Foo{
       Name:        name,
       Description: desc,
       Body:        body,
    })
    if err != nil {
        // handle error
    }
    fmt.Printf("%s\n", string(jData))
}

Demo

这里的关键是json.RawMessage类型。这实际上告诉json.Marshal不应该对该值进行解组,因此它将被原样复制(作为[]byte)。如果您需要稍后在其他地方解组Body的值,您可以简单地这样做:

data := map[string]any{}
if err := json.Unmarshal([]byte(t.Body), &data); err != nil {
    // handle error
}
fmt.Printf("Unmarshalled: %#v\n", data)
e0bqpujr

e0bqpujr2#

你的json中有一个错字,删除body值周围的",它将被修复:

requestJson := fmt.Sprintf(`{"name": "%s","description": "%s","body": %s}`, Name, Desc, Body)

相关问题