Skip to content

Commit 3f60c98

Browse files
committed
fix(yaml): handled null values from JSON
contributes: go-swagger/go-swagger#2919 Signed-off-by: Frederic BIDON <[email protected]>
1 parent 80e31a2 commit 3f60c98

File tree

2 files changed

+38
-2
lines changed

2 files changed

+38
-2
lines changed

yaml.go

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import (
1818
"encoding/json"
1919
"fmt"
2020
"path/filepath"
21+
"reflect"
2122
"strconv"
2223

2324
"github.com/mailru/easyjson/jlexer"
@@ -245,7 +246,27 @@ func (s JSONMapSlice) MarshalYAML() (interface{}, error) {
245246
return yaml.Marshal(&n)
246247
}
247248

249+
func isNil(input interface{}) bool {
250+
if input == nil {
251+
return true
252+
}
253+
kind := reflect.TypeOf(input).Kind()
254+
switch kind { //nolint:exhaustive
255+
case reflect.Ptr, reflect.Map, reflect.Slice, reflect.Chan:
256+
return reflect.ValueOf(input).IsNil()
257+
default:
258+
return false
259+
}
260+
}
261+
248262
func json2yaml(item interface{}) (*yaml.Node, error) {
263+
if isNil(item) {
264+
return &yaml.Node{
265+
Kind: yaml.ScalarNode,
266+
Value: "null",
267+
}, nil
268+
}
269+
249270
switch val := item.(type) {
250271
case JSONMapSlice:
251272
var n yaml.Node
@@ -318,9 +339,9 @@ func json2yaml(item interface{}) (*yaml.Node, error) {
318339
Tag: yamlBoolScalar,
319340
Value: strconv.FormatBool(val),
320341
}, nil
342+
default:
343+
return nil, fmt.Errorf("unhandled type: %T", val)
321344
}
322-
323-
return nil, nil //nolint:nilnil
324345
}
325346

326347
// JSONMapItem represents the value of a key in a JSON object held by JSONMapSlice

yaml_test.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,21 @@ tag:
6060

6161
}
6262

63+
func TestJSONToYAMLWithNull(t *testing.T) {
64+
const (
65+
jazon = `{"1":"the int key value","name":null,"y":"some value"}`
66+
expected = `"1": the int key value
67+
name: null
68+
y: some value
69+
`
70+
)
71+
var data JSONMapSlice
72+
require.NoError(t, json.Unmarshal([]byte(jazon), &data))
73+
ny, err := data.MarshalYAML()
74+
require.NoError(t, err)
75+
assert.Equal(t, expected, string(ny.([]byte)))
76+
}
77+
6378
func TestYAMLToJSON(t *testing.T) {
6479

6580
sd := `---

0 commit comments

Comments
 (0)