Skip to content

Encoding nil pointer to struct containing exported function leads to marshalling error #207

Closed
@timoreimann

Description

@timoreimann

I believe to have discovered an inconsistency in behavior between json-iterator and stdlib's encoding/json package.

Specifically, if you try to marshal a pointer to a struct which contains a function field, json-iterator returns an error from Marshal whereas the same method on encoding/json does not. To better illustrate, I have put together an example repository where the main.go file looks like this:

package main

import (
	encjson "encoding/json"
	"fmt"
	"os"

	"github.com/json-iterator/go"
)

type str struct {
	F func()
}

func main() {
	var s *str = nil

	var json = jsoniter.ConfigCompatibleWithStandardLibrary
	if _, err := json.Marshal(s); err != nil {
		fmt.Fprintf(os.Stderr, "json-iterator: marshalling failed: %s\n", err)
	} else {
		fmt.Println("json-iterator: marshalling succeeded.")
	}

	if _, err := encjson.Marshal(s); err != nil {
		fmt.Fprintf(os.Stderr, "encoding/json: marshalling failed: %s\n", err)
	} else {
		fmt.Println("encoding/json: marshalling succeeded.")
	}
}

Executing the application, the output is:

$ go run main.go
json-iterator: marshalling failed: [optional]: [main.str]: unsupported type: func()
encoding/json: marshalling succeeded.

Note that adding tags to ignore the function field might work in this artificial example but not in the general case. In fact, I ran into this issue while trying to marshal a struct holding a pointer to a tls.Config struct. This struct holds a Time func() time.Time field and produces the following error message during Marshal:

[tls.Config]: unsupported type: func() time.Time

Obviously, I cannot add tags to a struct embedded in the stdlib.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions