Repository: lyraproj/hiera (go)

Issue:
--render-as json fails on empty map
hiera.yaml
```yaml
version: 5
defaults:
  data_hash: yaml_data
  datadir: data
hierarchy:
  - name: global
    path: global.yaml
```

global.yaml
```yaml
empty_map: {}
```

```
lookup empty_map --render-as json
Error: json: unsupported type: map[interface {}]interface {}
```

Pull request description:
Handle special case of rendring an empty map in JSON
An empty map is reflected into the type `map[interface{}]interface{}`
by pcore. This is correct. There's no way of deciding key or value
type of an empty map. JSON is however only capable of marshaling
maps with string keys. This commit ensures that the corner case that
occurs for empty maps are handled correctly.

Closes #45

Patch:
diff --git a/hiera/render.go b/hiera/render.go
index 02f8ae1..16ddd3b 100644
--- a/hiera/render.go
+++ b/hiera/render.go
@@ -43,6 +43,10 @@ func Render(c px.Context, renderAs RenderName, value px.Value, out io.Writer) {
 		if renderAs == `yaml` {
 			bs, err = yaml.Marshal(v)
 		} else {
+			// JSON is not able to handle the result of reflecting an empty untyped map.
+			if em, ok := v.(map[interface{}]interface{}); ok && len(em) == 0 {
+				v = map[string]interface{}{}
+			}
 			bs, err = json.Marshal(v)
 		}
 		if err != nil {


Test patch:
diff --git a/lookup/lookup_test.go b/lookup/lookup_test.go
index 332998b..c60a0f2 100644
--- a/lookup/lookup_test.go
+++ b/lookup/lookup_test.go
@@ -111,6 +111,14 @@ func TestLookup_nullentry(t *testing.T) {
 	})
 }
 
+func TestLookup_emptyMap(t *testing.T) {
+	inTestdata(func() {
+		result, err := cli.ExecuteLookup(`--config`, `empty_map.yaml`, `--render-as`, `json`, `empty_map`)
+		require.NoError(t, err)
+		require.Equal(t, "{}", string(result))
+	})
+}
+
 func TestLookup_explain(t *testing.T) {
 	inTestdata(func() {
 		result, err := cli.ExecuteLookup(`--explain`, `--facts`, `facts.yaml`, `interpolate_ca`)
diff --git a/lookup/testdata/empty_map.yaml b/lookup/testdata/empty_map.yaml
new file mode 100644
index 0000000..5e2a7bd
--- /dev/null
+++ b/lookup/testdata/empty_map.yaml
@@ -0,0 +1,6 @@
+version: 5
+defaults:
+  datadir: hiera
+hierarchy:
+  - name: empty
+    path: empty_map.yaml
diff --git a/lookup/testdata/hiera/empty_map.yaml b/lookup/testdata/hiera/empty_map.yaml
new file mode 100644
index 0000000..2e81f50
--- /dev/null
+++ b/lookup/testdata/hiera/empty_map.yaml
@@ -0,0 +1,1 @@
+empty_map: {}
\ No newline at end of file