0

am having some troubles unmarshalling some content into a struct object in go. Basically, my struct is defined as:

 type TheParam struct {
    Id       string `json:"id,string"`
    Provider string `json:"provider,string"`
}

Now, I have one variable with the bytes, if I make fmt.Print(string(data)) then I get:

"{\"id\":\"some-id\",\"provider\":\"any-provider\"}"

An example of he data in bytes is:

34 123 92 34 105 100 92 34 58 92 34 103 105 116 104 117 98 45 100 97 115 104 45 97 99 99 101 115 115 92 34 44 92 34 112 114 111 118 105 100 101 114 92 34 58 92 34 103 105 116 104 117 98 92 34 125 34

And, am making the unmarshalling with:

if err = json.Unmarshal(data, &myParam); err != nil {
        redisLogger.WithError(err).Error("unmarshalling into interface")
    }

So, now am getting: json: cannot unmarshal string into Go value of type TheParam. What am I missing?

1
  • 2
    The error returned from json.Unmarshal describes the error in the JSON tags. Commented Sep 7, 2020 at 22:50

2 Answers 2

2

The string itself is encoded json value, so first you need to decode it into a string and then decode this value into the struct: https://play.golang.org/p/qSOd1O9fOSQ

Also please pay attention to the changed tags of the struct type. You don't need to use type specification in tag. It would be defined for you automatically.

Sign up to request clarification or add additional context in comments.

Comments

1

The string struct tag is redundant as you already defined the type in the struct.

This Playground should work:

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

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.