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

Add helpers for slice of Map #102

Merged
merged 2 commits into from
Feb 8, 2021
Merged
Changes from 1 commit
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
Next Next commit
Add helpers for slice of Map
objx can't work with JSON documents starting with top-level array. This
commit adds helpers FromJSONSlice and MustJSONSlice. Those returns `[]Map`
enabling objx usage for this case as well.
vyskocilm committed Feb 4, 2021
commit 215aca184653200b35eb0422671130e02dd6dbfe
28 changes: 28 additions & 0 deletions map.go
Original file line number Diff line number Diff line change
@@ -92,6 +92,18 @@ func MustFromJSON(jsonString string) Map {
return o
}

// MustFromJSONSlice creates a new slice of Map containing the data specified in the
// jsonString. Works with jsons with a top level array
//
// Panics if the JSON is invalid.
func MustFromJSONSlice(jsonString string) []Map {
slice, err := FromJSONSlice(jsonString)
if err != nil {
panic("objx: MustFromJSONSlice failed with error: " + err.Error())
}
return slice
}

// FromJSON creates a new Map containing the data specified in the
// jsonString.
//
@@ -106,6 +118,22 @@ func FromJSON(jsonString string) (Map, error) {
return m, nil
}

// FromJSONSlice creates a new slice of Map containing the data specified in the
// jsonString. Works with jsons with a top level array
//
// Returns an error if the JSON is invalid.
func FromJSONSlice(jsonString string) ([]Map, error) {
var slice []Map
err := json.Unmarshal([]byte(jsonString), &slice)
if err != nil {
return nil, err
geseq marked this conversation as resolved.
Show resolved Hide resolved
}
for _, m := range slice {
m.tryConvertFloat64()
}
return slice, nil
}

func (m Map) tryConvertFloat64() {
for k, v := range m {
switch v.(type) {
19 changes: 19 additions & 0 deletions map_test.go
Original file line number Diff line number Diff line change
@@ -225,3 +225,22 @@ func TestMapFromURLQueryWithError(t *testing.T) {
objx.MustFromURLQuery("%")
})
}

func TestJSONTopLevelSlice(t *testing.T) {
slice, err := objx.FromJSONSlice(`[{"id": 10000001}, {"id": 42}]`)

assert.NoError(t, err)
require.Len(t, slice, 2)
assert.Equal(t, 10000001, slice[0].Get("id").MustInt())
assert.Equal(t, 42, slice[1].Get("id").MustInt())
}

func TestJSONTopLevelSliceWithError(t *testing.T) {
slice, err := objx.FromJSONSlice(`{"id": 10000001}`)

assert.Error(t, err)
assert.Nil(t, slice)
assert.Panics(t, func() {
_ = objx.MustFromJSONSlice(`{"id": 10000001}`)
})
}