Browse Source

feat: Adding conversion helper for JSON objects

Matthias Ladkau 3 years ago
parent
commit
0454de30f3
2 changed files with 50 additions and 0 deletions
  1. 29 0
      scope/helper.go
  2. 21 0
      scope/helper_test.go

+ 29 - 0
scope/helper.go

@@ -63,3 +63,32 @@ func ToScope(name string, o map[interface{}]interface{}) parser.Scope {
 	}
 	return vs
 }
+
+/*
+ConvertJSONToECALObject converts a JSON container structure into an object which
+can be used by ECAL.
+*/
+func ConvertJSONToECALObject(v interface{}) interface{} {
+	res := v
+
+	if mapContainer, ok := v.(map[string]interface{}); ok {
+		newRes := make(map[interface{}]interface{})
+
+		for mk, mv := range mapContainer {
+			newRes[mk] = ConvertJSONToECALObject(mv)
+		}
+
+		res = newRes
+
+	} else if mapList, ok := v.([]interface{}); ok {
+		newRes := make([]interface{}, len(mapList))
+
+		for i, lv := range mapList {
+			newRes[i] = ConvertJSONToECALObject(lv)
+		}
+
+		res = newRes
+	}
+
+	return res
+}

+ 21 - 0
scope/helper_test.go

@@ -11,6 +11,7 @@
 package scope
 
 import (
+	"fmt"
 	"testing"
 
 	"devt.de/krotik/ecal/parser"
@@ -39,3 +40,23 @@ func TestScopeConversion(t *testing.T) {
 		return
 	}
 }
+
+func TestConvertJSONToECALObject(t *testing.T) {
+
+	testJSONStructure := map[string]interface{}{
+		"foo": []interface{}{
+			map[string]interface{}{
+				"bar": "123",
+			},
+		},
+	}
+
+	res := ConvertJSONToECALObject(testJSONStructure)
+
+	if typeString := fmt.Sprintf("%#v", res); typeString !=
+		`map[interface {}]interface {}{"foo":[]interface {}{map[interface {}]interface {}{"bar":"123"}}}` {
+		t.Error("Unexpected result:", typeString)
+		return
+	}
+
+}