Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
timoreimann opened this issue Dec 14, 2017 · 1 comment

Comments

@timoreimann
Copy link

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.

@taowen taowen closed this as completed in a9b9c73 Dec 15, 2017
@timoreimann
Copy link
Author

@taowen thanks for the prompt fix!

zhenzou pushed a commit to zhenzou/jsoniter that referenced this issue Feb 2, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant