Skip to content

MarshalJSON marshals to an empty {} for value types #60

Description

@OmarTariq612

Unmarshaling works flawlessly, but when marshaling a value (not a pointer) the outcome is {} because MarshalJSON is implemented for a pointer reciever not a value reciever, is this intended ? if so, could you explain why is it implemented that way ?

Using this example: here is the playground link: https://go.dev/play/p/59r5A-OJtUl

package main

import (
	"encoding/json"
	"fmt"

	orderedmap "github.com/wk8/go-ordered-map/v2"
)

func main() {
	b := []byte(`
	{
		"key_1": "value_1",
		"key_2": "value_2"
	}
	`)

	var s orderedmap.OrderedMap[string, string]
	if err := json.Unmarshal(b, &s); err != nil {
		panic(err)
	}

	for pair := s.Oldest(); pair != nil; pair = pair.Next() {
		fmt.Println(pair.Key, pair.Value)
		// this prints:
		// key_1 value_1
		// key_2 value_2
	}

	b, err := json.Marshal(s)
	if err != nil {
		panic(err)
	}

	fmt.Println(string(b)) // this prints: {}
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions