File tree Expand file tree Collapse file tree 2 files changed +38
-2
lines changed Expand file tree Collapse file tree 2 files changed +38
-2
lines changed Original file line number Diff line number Diff line change @@ -18,6 +18,7 @@ import (
18
18
"encoding/json"
19
19
"fmt"
20
20
"path/filepath"
21
+ "reflect"
21
22
"strconv"
22
23
23
24
"github.com/mailru/easyjson/jlexer"
@@ -245,7 +246,27 @@ func (s JSONMapSlice) MarshalYAML() (interface{}, error) {
245
246
return yaml .Marshal (& n )
246
247
}
247
248
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
+
248
262
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
+
249
270
switch val := item .(type ) {
250
271
case JSONMapSlice :
251
272
var n yaml.Node
@@ -318,9 +339,9 @@ func json2yaml(item interface{}) (*yaml.Node, error) {
318
339
Tag : yamlBoolScalar ,
319
340
Value : strconv .FormatBool (val ),
320
341
}, nil
342
+ default :
343
+ return nil , fmt .Errorf ("unhandled type: %T" , val )
321
344
}
322
-
323
- return nil , nil //nolint:nilnil
324
345
}
325
346
326
347
// JSONMapItem represents the value of a key in a JSON object held by JSONMapSlice
Original file line number Diff line number Diff line change 60
60
61
61
}
62
62
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
+
63
78
func TestYAMLToJSON (t * testing.T ) {
64
79
65
80
sd := `---
You can’t perform that action at this time.
0 commit comments