How to parse JSON string to struct

2020-06-16 02:34发布

I have struct of Request, value is optional:

type Request struct {
    Operation string      `json:"operation"`
    Key string            `json:"key"`
    Value string          `json:"value"`
}

And function that should parse json string to struct^

go func() {
    s := string("{'operation': 'get', 'key': 'example'}")
    data := Request{}
    json.Unmarshal([]byte(s), data)
    log.Printf("Operation: %s", data.Operation)
}

For some reason data.Operation is empty. What is wrong here?

标签: json parsing go
1条回答
女痞
2楼-- · 2020-06-16 03:31

Two problems, first, your json is invalid, it needs to use " instead of '

Second, you have to unmarshal into &data and not to data

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

package main

import (
    "fmt"
    "encoding/json"
)

type Request struct {
    Operation string      `json:"operation"`
    Key string            `json:"key"`
    Value string          `json:"value"`
}

func main() {
    s := string(`{"operation": "get", "key": "example"}`)
    data := Request{}
    json.Unmarshal([]byte(s), &data)
    fmt.Printf("Operation: %s", data.Operation)
}

Side note, you would have seen this, if you would have been checking your errors:

err := json.Unmarshal([]byte(s), data)
if err != nil {
    fmt.Println(err.Error()) 
    //json: Unmarshal(non-pointer main.Request)
}

s := string("{'operation': 'get', 'key': 'example'}")
//...
err := json.Unmarshal([]byte(s), data)
if err != nil {
    fmt.Println(err.Error()) 
    //invalid character '\'' looking for beginning of object key string
}
查看更多
登录 后发表回答