elliotchance / orderedmap

🔃 An ordered map in Go with amortized O(1) for Set, Get, Delete and Len.
MIT License
817 stars 62 forks source link

Support JSON marshal #28

Open MrMarble opened 2 years ago

MrMarble commented 2 years ago

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: https://github.com/golang/go/issues/46477


This change is Reviewable

elliotchance commented 2 years ago

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))
}
MrMarble commented 2 years ago

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 commented 2 years ago

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.