Skip to content

Commit

Permalink
Add JSONObjectToYAMLObject
Browse files Browse the repository at this point in the history
  • Loading branch information
sttts committed Feb 28, 2019
1 parent fd68e98 commit f7df8d8
Showing 1 changed file with 44 additions and 0 deletions.
44 changes: 44 additions & 0 deletions yaml.go
Original file line number Diff line number Diff line change
Expand Up @@ -317,3 +317,47 @@ func convertToJSONableObject(yamlObj interface{}, jsonTarget *reflect.Value) (in
return yamlObj, nil
}
}

// JSONObjectToYAMLObject converts an in-memory JSON object into a YAML in-memory MapSlice,
// without going through a byte representation.
func JSONObjectToYAMLObject(j map[string]interface{}) yaml.MapSlice {
if j == nil {
return nil
}
ret := make(yaml.MapSlice, 0, len(j))
for k, v := range j {
ret = append(ret, yaml.MapItem{k, jsonToYAMLValue(v)})
}
return ret
}

func jsonToYAMLValue(j interface{}) interface{} {
switch j := j.(type) {
case map[string]interface{}:
return JSONObjectToYAMLObject(j)
case []interface{}:
ret := make([]interface{}, len(j))
for i := range j {
ret[i] = jsonToYAMLValue(j[i])
}
return ret
case float64:
// replicate the logic in https://github.com/go-yaml/yaml/blob/51d6538a90f86fe93ac480b35f37b2be17fef232/resolve.go#L151
if i64 := int64(j); j == float64(i64) {
if i := int(i64); i64 == int64(i) {
return i
}
return i64
}
if ui64 := uint64(j); j == float64(ui64) {
return ui64
}
return j
case int64:
if i := int(j); j == int64(i) {
return i
}
return j
}
return j
}

0 comments on commit f7df8d8

Please sign in to comment.