Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Merged
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
28 changes: 28 additions & 0 deletions map.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
//
Expand All @@ -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
}
for _, m := range slice {
m.tryConvertFloat64()
}
return slice, nil
}

func (m Map) tryConvertFloat64() {
for k, v := range m {
switch v.(type) {
Expand Down
19 changes: 19 additions & 0 deletions map_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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}`)
})
}