From 3beee3f8047d3daaaebf378372f95db1a622c139 Mon Sep 17 00:00:00 2001 From: kenjones Date: Thu, 21 Sep 2017 12:01:03 -0400 Subject: [PATCH] Bugfix: Panic on non-string keys Adds check if the key is an `int` or `bool`, and converts to a string as part of the `toJSON` function. Test cases added. Resolves: #28 --- json_converter.go | 12 ++++++++++-- json_converter_test.go | 18 ++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/json_converter.go b/json_converter.go index 933be9ed..756b5f0b 100644 --- a/json_converter.go +++ b/json_converter.go @@ -2,7 +2,9 @@ package main import ( "encoding/json" - "gopkg.in/yaml.v2" + "strconv" + + yaml "gopkg.in/yaml.v2" ) func jsonToString(context interface{}) string { @@ -26,7 +28,13 @@ func toJSON(context interface{}) interface{} { oldMap := context.(yaml.MapSlice) newMap := make(map[string]interface{}) for _, entry := range oldMap { - newMap[entry.Key.(string)] = toJSON(entry.Value) + if str, ok := entry.Key.(string); ok { + newMap[str] = toJSON(entry.Value) + } else if i, ok := entry.Key.(int); ok { + newMap[strconv.Itoa(i)] = toJSON(entry.Value) + } else if b, ok := entry.Key.(bool); ok { + newMap[strconv.FormatBool(b)] = toJSON(entry.Value) + } } return newMap default: diff --git a/json_converter_test.go b/json_converter_test.go index 0a1adfb2..102066be 100644 --- a/json_converter_test.go +++ b/json_converter_test.go @@ -13,6 +13,24 @@ b: assertResult(t, "{\"b\":{\"c\":2}}", jsonToString(data)) } +func TestJsonToString_withIntKey(t *testing.T) { + var data = parseData(` +--- +b: + 2: c +`) + assertResult(t, `{"b":{"2":"c"}}`, jsonToString(data)) +} + +func TestJsonToString_withBoolKey(t *testing.T) { + var data = parseData(` +--- +b: + false: c +`) + assertResult(t, `{"b":{"false":"c"}}`, jsonToString(data)) +} + func TestJsonToString_withArray(t *testing.T) { var data = parseData(` ---