Home > Blockchain >  Go json.Unmarshal does not work with type definition of json.RawMessage
Go json.Unmarshal does not work with type definition of json.RawMessage

Time:02-11

I have a small Go program like this:

package main

import "encoding/json"

func main() {
    bs := []byte(`{"items": ["foo", "bar"]}`)

    data := Data{}
    err := json.Unmarshal(bs, &data)
    if err != nil {
        panic(err)
    }
}

type Data struct {
    Items []Raw `json:"items"`
}

// If I do this, this program panics with "illegal base64 data at input byte 0"
type Raw json.RawMessage

// This works
type Raw = json.RawMessage

Why does json.Unmarshal work with type alias but not type definition? What does that error message mean?

CodePudding user response:

This is a new type definition:

type Raw json.RawMessage

The Raw type is derived from json.RawMessage, but it is a new type without any of the methods defined for json.RawMessage. So, if json.RawMessage has a json unmarshaler method, Raw does not have that. Code such as following will not recognize a variable t of type Raw as a json.RawMessage:

if t, ok:=item.(json.RawMessage); ok {
  ...
}

This is a type alias:

type Raw = json.RawMessage

Here, Raw has all the methods json.RawMessage has, and type assertion to json.RawMessage will work, because Raw is simply another name for json.RawMessage.

  •  Tags:  
  • go
  • Related