mirror of
https://github.com/Luzifer/go_helpers.git
synced 2024-12-24 13:01:21 +00:00
Add a YAML to JSON converter as yaml-helper
Signed-off-by: Knut Ahlers <knut@ahlers.me>
This commit is contained in:
parent
94b91ff63a
commit
16d0025db9
2 changed files with 78 additions and 0 deletions
46
yaml/tojson.go
Normal file
46
yaml/tojson.go
Normal file
|
@ -0,0 +1,46 @@
|
||||||
|
package yaml
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
|
||||||
|
yaml "gopkg.in/yaml.v2"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ToJSON takes an io.Reader containing YAML source and converts it into
|
||||||
|
// a JSON representation of the YAML object.
|
||||||
|
func ToJSON(in io.Reader) (io.Reader, error) {
|
||||||
|
var body interface{}
|
||||||
|
|
||||||
|
if err := yaml.NewDecoder(in).Decode(&body); err != nil {
|
||||||
|
return nil, fmt.Errorf("Unable to unmarshal YAML: %s", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
body = convert(body)
|
||||||
|
|
||||||
|
var buf = new(bytes.Buffer)
|
||||||
|
if err := json.NewEncoder(buf).Encode(body); err != nil {
|
||||||
|
return nil, fmt.Errorf("Unable to marshal JSON: %s", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return buf, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Source: https://stackoverflow.com/a/40737676/1741281
|
||||||
|
func convert(i interface{}) interface{} {
|
||||||
|
switch x := i.(type) {
|
||||||
|
case map[interface{}]interface{}:
|
||||||
|
m2 := map[string]interface{}{}
|
||||||
|
for k, v := range x {
|
||||||
|
m2[k.(string)] = convert(v)
|
||||||
|
}
|
||||||
|
return m2
|
||||||
|
case []interface{}:
|
||||||
|
for i, v := range x {
|
||||||
|
x[i] = convert(v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return i
|
||||||
|
}
|
32
yaml/tojson_test.go
Normal file
32
yaml/tojson_test.go
Normal file
|
@ -0,0 +1,32 @@
|
||||||
|
package yaml
|
||||||
|
|
||||||
|
import (
|
||||||
|
"io/ioutil"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestToJSON(t *testing.T) {
|
||||||
|
src := `Services:
|
||||||
|
- Orders:
|
||||||
|
- ID: $save ID1
|
||||||
|
SupplierOrderCode: $SupplierOrderCode
|
||||||
|
- ID: $save ID2
|
||||||
|
SupplierOrderCode: 111111
|
||||||
|
`
|
||||||
|
|
||||||
|
expected := `{"Services":[{"Orders":[{"ID":"$save ID1","SupplierOrderCode":"$SupplierOrderCode"},{"ID":"$save ID2","SupplierOrderCode":111111}]}]}
|
||||||
|
`
|
||||||
|
|
||||||
|
j, err := ToJSON(strings.NewReader(src))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("ToJSON failed: %s", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
real, _ := ioutil.ReadAll(j)
|
||||||
|
realString := string(real)
|
||||||
|
|
||||||
|
if expected != realString {
|
||||||
|
t.Errorf("Expected JSON was not created:\nEXPE: %q\nREAL: %q", expected, realString)
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in a new issue