From 43f1b5ae4a8ca6ea7bc0127069dd2c0419775452 Mon Sep 17 00:00:00 2001 From: Ben Schumacher Date: Mon, 29 Jan 2018 18:05:25 +0100 Subject: [PATCH 1/2] Fix bug introduced with #17 --- map_test.go | 15 +++++++++++++++ type_specific_codegen.go | 17 ++++++++++++----- 2 files changed, 27 insertions(+), 5 deletions(-) diff --git a/map_test.go b/map_test.go index 6036cbb..f743d94 100644 --- a/map_test.go +++ b/map_test.go @@ -116,6 +116,21 @@ func TestConversionJSONInt(t *testing.T) { assert.Equal(t, []interface{}{1}, m.Get("d").InterSlice()[0]) } +func TestJSONSlice(t *testing.T) { + jsonString := + `{ + "a": [ + {"b": 1}, + {"c": 2} + ] + }` + m, err := objx.FromJSON(jsonString) + + assert.Nil(t, err) + require.NotNil(t, m) + assert.Equal(t, []objx.Map{objx.Map{"b": 1}, objx.Map{"c": 2}}, m.Get("a").ObjxMapSlice()) +} + func TestMapFromBase64String(t *testing.T) { base64String := "eyJuYW1lIjoiTWF0In0=" o, err := objx.FromBase64(base64String) diff --git a/type_specific_codegen.go b/type_specific_codegen.go index 74627ca..de42409 100644 --- a/type_specific_codegen.go +++ b/type_specific_codegen.go @@ -276,7 +276,10 @@ func (v *Value) MustObjxMap() Map { // ObjxMapSlice gets the value as a [](Map), returns the optionalDefault // value or nil if the value is not a [](Map). func (v *Value) ObjxMapSlice(optionalDefault ...[](Map)) [](Map) { - slice, ok := v.data.([]interface{}) + if s, ok := v.data.([]Map); ok { + return s + } + s, ok := v.data.([]interface{}) if !ok { if len(optionalDefault) == 1 { return optionalDefault[0] @@ -285,11 +288,15 @@ func (v *Value) ObjxMapSlice(optionalDefault ...[](Map)) [](Map) { } } - result := make([]Map, len(slice)) - for i := range slice { - result[i] = New(slice[i]) + result := make([]Map, len(s)) + for i := range s { + switch s[i].(type) { + case Map: + result[i] = s[i].(Map) + default: + return nil + } } - return result } From 884f9f5c883e522cd8b703ef03ff1d09bd559117 Mon Sep 17 00:00:00 2001 From: Ben Schumacher Date: Mon, 29 Jan 2018 18:13:06 +0100 Subject: [PATCH 2/2] Add testcase for mixed json slice --- map_test.go | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/map_test.go b/map_test.go index f743d94..5cda629 100644 --- a/map_test.go +++ b/map_test.go @@ -116,7 +116,7 @@ func TestConversionJSONInt(t *testing.T) { assert.Equal(t, []interface{}{1}, m.Get("d").InterSlice()[0]) } -func TestJSONSlice(t *testing.T) { +func TestJSONSliceInt(t *testing.T) { jsonString := `{ "a": [ @@ -131,6 +131,22 @@ func TestJSONSlice(t *testing.T) { assert.Equal(t, []objx.Map{objx.Map{"b": 1}, objx.Map{"c": 2}}, m.Get("a").ObjxMapSlice()) } +func TestJSONSliceMixed(t *testing.T) { + jsonString := + `{ + "a": [ + {"b": 1}, + "a" + ] + }` + m, err := objx.FromJSON(jsonString) + + assert.Nil(t, err) + require.NotNil(t, m) + + assert.Nil(t, m.Get("a").ObjxMapSlice()) +} + func TestMapFromBase64String(t *testing.T) { base64String := "eyJuYW1lIjoiTWF0In0=" o, err := objx.FromBase64(base64String)