Skip to content
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

Support JSON marshal #28

Open
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

MrMarble
Copy link

@MrMarble MrMarble commented Jul 19, 2022

Great library!

I've read your comment on PR #16 about creating a type alias to implement JSON marshal, but with v2 generics that isn't possible:

type omap = orderedmap.OrderedMap // Err: cannot use generic type orderedmap.OrderedMap[K constraints.Ordered, V any] without instantiation

// with instantiation
type omap = orderedmap.OrderedMap[string, any]

func (m *omap) MarshalJSON() ([]byte, error) { // Err: cannot define methods on instantiated type *orderedmap.OrderedMap[string, any]
	return nil, nil
}

It is being discussed here: golang/go#46477


This change is Reviewable

@elliotchance
Copy link
Owner

On way around this is just to encapsulate the map if you want a specific type (https://go.dev/play/p/HgIkJgoI5zF):

package main

import (
	"encoding/json"
	"fmt"

	"github.com/elliotchance/orderedmap/v2"
)

type OrderedStringMap struct {
	*orderedmap.OrderedMap[string, any]
}

func (m *OrderedStringMap) MarshalJSON() ([]byte, error) {
	return []byte("null"), nil
}

func main() {
	m := &OrderedStringMap{orderedmap.NewOrderedMap[string, any]()}
	m.Set("foo", 123)

	data, _ := json.Marshal(m)
	fmt.Println(string(data))
}

Or, you can even use generics in the same way (https://go.dev/play/p/PKUSYsxiHHh):

type JSONOrderedMap[K constraints.Ordered, V any] struct {
	*orderedmap.OrderedMap[K, V]
}

func (m JSONOrderedMap[K, V]) MarshalJSON() ([]byte, error) {
	return []byte("null"), nil
}

func main() {
	m := &JSONOrderedMap[string, any]{orderedmap.NewOrderedMap[string, any]()}
	m.Set("foo", 123)

	data, _ := json.Marshal(m)
	fmt.Println(string(data))
}

@@ -152,3 +155,28 @@ func (m *OrderedMap[K, V]) Copy() *OrderedMap[K, V] {

return m2
}

// Implements JSON marshaling.
func (m *OrderedMap[string, V]) MarshalJSON() ([]byte, error) {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure how I feel about this for a few reasons:

  1. It only works with string keys. Which I'm sure is a common case, but I don't want to get into needing to do a method for every common type.
  2. It's not symmetrical (there is no decode/unmarshal).
  3. It's quite opinionated in the way that it's doing the encode. Specifically, it creates a JSON object that is ambiguous because some systems that ingest this ordered data (for example, Go itself) which will not reasonably be able to restore the order so information will be lost.

I think a more appropriate way to deal with this is to have separate symmetrical types that can wrap depending on the functionality needed (basically what users have to do now) like:

type MyThingo struct {
     // Great for memory, but not able to serialize.
    map1 *orderedmap.OrderedMap[string, any]

    // I need to serialize this (and maintain order), but don't care
    // about the storage format. Like:
    //   [{"key":"foo","value":123}]
    map2 *orderedmap.OrderedSerializableMap[string, any]

    // I want to retain the order in memory, but I don't need to maintain
    // when when serialized/reduce foot print/increase readability by
    // other programs (probably a bad name for the type though). Like:
    //   {"foo",123}
    map3 *orderedmap.OrderedMapSerializeUnordered[string, any]
}

@MrMarble
Copy link
Author

On way around this is just to encapsulate the map if you want a specific type (https://go.dev/play/p/HgIkJgoI5zF):
....

Oh!, nice trick! I didn't know/though about that, I'm not an experienced Go programmer, I've been using it for some months. Knowing that resolves my problem and the motivation to make this PR.

  1. It only works with string keys. Which I'm sure is a common case, but I don't want to get into needing to do a method for every common type.

I made that change last minute because at the end the JSON schema specifies that keys must be strings, but I recon that it should follow the generic declaration.

  1. It's not symmetrical (there is no decode/unmarshal).

Yes, I know, I wanted to make sure you liked my approach before doing it because the unmarshal part is a bit more complicated (more code needed). I'm working on it.

I think a more appropriate way to deal with this is to have separate symmetrical types that can wrap depending on the functionality needed (basically what users have to do now)

That's actually a better idea than mine, but for my use-case I needed a standard JSON, not the {"key": "foo", "value": "bar"} format.
That said, knowing I can wrap your ordered map inside a struct to implement my own marshal function, there's no need to implement my approach and instead do yours.

I'm willing to help!

@elliotchance
Copy link
Owner

If you're looking to contribute, I'd be OK with either (or both) of these changes (fi you decide to do both please put in separate PRs):

  1. The default orderedmap implementation can have a JSON marhshal/unmarshal of [["key1", "value1"], ["key2", "value2"]...]. This will at least let the ordermap be serialized in a lossless way.
  2. Provide a new type that will JSON encode to an object (ie. {"key1": "value1", ...} but make it clear in the docs that it will not retain the order when marshalled or unmarshalled. The key should be strictly string but the value can be any.

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

Successfully merging this pull request may close these issues.

2 participants