@@ -17,13 +17,14 @@ package unstructuredutils
1717
1818import (
1919 "bufio"
20+ "bytes"
2021 "errors"
2122 "fmt"
2223 "io"
2324 "os"
24- "strings"
2525
2626 "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
27+ "k8s.io/apimachinery/pkg/runtime"
2728 utilruntime "k8s.io/apimachinery/pkg/util/runtime"
2829 "k8s.io/apimachinery/pkg/util/yaml"
2930 "k8s.io/client-go/kubernetes/scheme"
@@ -44,28 +45,29 @@ func ReadFile(filename string) ([]unstructured.Unstructured, error) {
4445 return Read (f )
4546}
4647
47- // Read treats io.Reader as an incoming YAML stream and reads all unstructured.Unstructured objects of it.
48+ // Read treats io.Reader as an incoming YAML or JSON stream and reads all unstructured.Unstructured objects of it.
4849//
49- // The YAML has to be well-formed multi-document YAML separated with the separator '---'.
50+ // The document has to be well-formed. For multi-doc YAMLs, '---' is used as separator .
5051// Empty sub-documents are filtered from the resulting list.
5152func Read (r io.Reader ) ([]unstructured.Unstructured , error ) {
52- rd := yaml .NewYAMLReader (bufio .NewReader (r ))
53+ d := yaml .NewYAMLOrJSONDecoder (bufio .NewReader (r ), 4096 )
5354 var objs []unstructured.Unstructured
5455 for {
55- data , err := rd . Read ()
56- if err != nil {
56+ ext := runtime. RawExtension {}
57+ if err := d . Decode ( & ext ); err != nil {
5758 if ! errors .Is (io .EOF , err ) {
58- return nil , fmt .Errorf ("error reading YAML : %w" , err )
59+ return nil , fmt .Errorf ("error parsing : %w" , err )
5960 }
6061 return objs , nil
6162 }
6263
63- if strings .TrimSpace (string (data )) == "" {
64+ ext .Raw = bytes .TrimSpace (ext .Raw )
65+ if len (ext .Raw ) == 0 || bytes .Equal (ext .Raw , []byte ("null" )) {
6466 continue
6567 }
6668
6769 obj := & unstructured.Unstructured {}
68- if _ , _ , err := scheme .Codecs .UniversalDeserializer ().Decode (data , nil , obj ); err != nil {
70+ if _ , _ , err := scheme .Codecs .UniversalDeserializer ().Decode (ext . Raw , nil , obj ); err != nil {
6971 return nil , fmt .Errorf ("invalid object: %w" , err )
7072 }
7173
0 commit comments