53

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?

2
  • 2
    You also have a go keyword with without a function call. If that's a typo missing the (), you then have a goroutine without any synchronization. Commented Nov 13, 2017 at 18:00
  • 7
    As is one of the most common issues out there, don't ignore errors. json.Unmarshal returns an error type. The output of that error would have told you that your json had invalid quotes, and after you fixed that, would have told you that your destination variable needed to be a pointer. Commented Nov 13, 2017 at 18:30

1 Answer 1

123

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:

s := string("{'operation': 'get', 'key': 'example'}")

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

err := json.Unmarshal([]byte(s), &data)
if err != nil {
    fmt.Println(err.Error()) 
    //invalid character '\'' looking for beginning of object key string
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.