Skip to content

Commit

Permalink
fix(yaml): handled null values from JSON
Browse files Browse the repository at this point in the history
contributes: go-swagger/go-swagger#2919

Signed-off-by: Frederic BIDON <fredbi@yahoo.com>
  • Loading branch information
fredbi committed Dec 21, 2023
1 parent 80e31a2 commit 3f60c98
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 2 deletions.
25 changes: 23 additions & 2 deletions yaml.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import (
"encoding/json"
"fmt"
"path/filepath"
"reflect"
"strconv"

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

func isNil(input interface{}) bool {
if input == nil {
return true
}
kind := reflect.TypeOf(input).Kind()
switch kind { //nolint:exhaustive
case reflect.Ptr, reflect.Map, reflect.Slice, reflect.Chan:
return reflect.ValueOf(input).IsNil()
default:
return false
}
}

func json2yaml(item interface{}) (*yaml.Node, error) {
if isNil(item) {
return &yaml.Node{
Kind: yaml.ScalarNode,
Value: "null",
}, nil
}

switch val := item.(type) {
case JSONMapSlice:
var n yaml.Node
Expand Down Expand Up @@ -318,9 +339,9 @@ func json2yaml(item interface{}) (*yaml.Node, error) {
Tag: yamlBoolScalar,
Value: strconv.FormatBool(val),
}, nil
default:
return nil, fmt.Errorf("unhandled type: %T", val)
}

return nil, nil //nolint:nilnil
}

// JSONMapItem represents the value of a key in a JSON object held by JSONMapSlice
Expand Down
15 changes: 15 additions & 0 deletions yaml_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,21 @@ tag:

}

func TestJSONToYAMLWithNull(t *testing.T) {
const (
jazon = `{"1":"the int key value","name":null,"y":"some value"}`
expected = `"1": the int key value
name: null
y: some value
`
)
var data JSONMapSlice
require.NoError(t, json.Unmarshal([]byte(jazon), &data))
ny, err := data.MarshalYAML()
require.NoError(t, err)
assert.Equal(t, expected, string(ny.([]byte)))
}

func TestYAMLToJSON(t *testing.T) {

sd := `---
Expand Down

0 comments on commit 3f60c98

Please sign in to comment.