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
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions v2/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,13 @@ module github.com/elliotchance/orderedmap/v2

go 1.18

require (
github.com/stretchr/testify v1.7.1
golang.org/x/exp v0.0.0-20220321173239-a90fa8a75705
)

require (
github.com/davecgh/go-spew v1.1.0 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/stretchr/testify v1.7.1 // indirect
golang.org/x/exp v0.0.0-20220321173239-a90fa8a75705 // indirect
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c // indirect
)
1 change: 1 addition & 0 deletions v2/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ github.com/stretchr/testify v1.7.1 h1:5TQK59W5E3v0r2duFAb7P95B6hEeOyEnHRa8MjYSMT
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
golang.org/x/exp v0.0.0-20220321173239-a90fa8a75705 h1:ba9YlqfDGTTQ5aZ2fwOoQ1hf32QySyQkR6ODGDzHlnE=
golang.org/x/exp v0.0.0-20220321173239-a90fa8a75705/go.mod h1:lgLbSvA5ygNOMpwM/9anMpWVlVJ7Z+cHWq/eFuinpGE=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
28 changes: 28 additions & 0 deletions v2/orderedmap.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
package orderedmap

import (
"bytes"
"container/list"
"encoding/json"

"golang.org/x/exp/constraints"
)

Expand Down Expand Up @@ -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]
}

if m.Len() == 0 {
return []byte("{}"), nil
}
var buf bytes.Buffer
buf.WriteByte('{')
encoder := json.NewEncoder(&buf)
for el := m.Front(); el != nil; el = el.Next() {
// add key
if err := encoder.Encode(el.Key); err != nil {
return nil, err
}
buf.WriteByte(':')
// add value
if err := encoder.Encode(el.Value); err != nil {
return nil, err
}
buf.WriteByte(',')
}
buf.Truncate(buf.Len() - 1)
buf.WriteByte('}')
return buf.Bytes(), nil
}
45 changes: 45 additions & 0 deletions v2/orderedmap_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package orderedmap_test

import (
"encoding/json"
"testing"

"github.com/elliotchance/orderedmap/v2"
Expand Down Expand Up @@ -249,3 +250,47 @@ func TestGetElement(t *testing.T) {
assert.Nil(t, element)
})
}

func TestOrderedMapJSON(t *testing.T) {
t.Run("EmptyMap", func(t *testing.T) {
m := orderedmap.NewOrderedMap[int, string]()
json, err := json.Marshal(m)

assert.NoError(t, err)
assert.Equal(t, `{}`, string(json))
})

t.Run("InvalidJSON", func(t *testing.T) {
m := orderedmap.NewOrderedMap[int, any]()
m.Set(1, struct{ Foo string }{"bar"})

_, err := json.Marshal(m)
assert.Error(t, err)
})

t.Run("MarshalJSON", func(t *testing.T) {
m := orderedmap.NewOrderedMap[string, any]()
m.Set("string", "foo")
m.Set("number", 1337)
m.Set("slice", []string{"foo", "bar"})
m.Set("map", map[string]string{"foo": "bar"})
m.Set("bool", true)
m.Set("nil", nil)
m.Set("struct", struct {
Foo string `json:"foo_tag"`
}{"bar"})

m2 := orderedmap.NewOrderedMap[string, any]()
m2.Set("string", "foo")
m2.Set("number", 1337)
m2.Set("slice", []string{"foo", "bar"})

m.Set("orderedMap", m2)

json, err := json.Marshal(m)

assert.NoError(t, err)
assert.Equal(t, `{"string":"foo","number":1337,"slice":["foo","bar"],"map":{"foo":"bar"},"bool":true,"nil":null,"struct":{"foo_tag":"bar"},"orderedMap":{"string":"foo","number":1337,"slice":["foo","bar"]}}`, string(json))
})

}