Files
x/encoding/json/obj.go
Colin Henry 54aae5f242
All checks were successful
Go / build (1.23) (push) Successful in 3m51s
big updates: tests, bug fixed, documentation. oh my
2026-01-03 15:53:50 -08:00

71 lines
1.3 KiB
Go
Executable File

package json
import (
"encoding/json"
std "encoding/json"
"io"
"os"
"git.sdf.org/jchenry/x"
)
type Object map[string]any
type Array []any
type Unknown struct {
Object *Object
Array *Array
}
func (u *Unknown) UnmarshalJSON(data []byte) error {
var err error
switch data[0] {
case '{':
u.Object = &Object{}
err = std.Unmarshal(data, u.Object)
case '[':
u.Array = &Array{}
err = std.Unmarshal(data, u.Array)
}
return err
}
func (u *Unknown) Resolve() any {
if u.Object != nil {
return u.Object
} else if u.Array != nil {
return u.Array
} else {
panic("unresolvable type")
}
}
func LoadJSONFromFileToType(jsn *os.File, v any) error {
x.Assert(jsn != nil, "LoadJSONFromFileToType: jsn is nil")
x.Assert(v != nil, "LoadJSONFromFileToType: v is nil")
jsnBytes, err := LoadJSONFromFile(jsn)
if err != nil {
return err
}
err = json.Unmarshal(jsnBytes, v)
if err != nil {
return err
}
return nil
}
func LoadJSONFromFile(jsn *os.File) (jsnString []byte, err error) {
x.Assert(jsn != nil, "LoadJSONFromFile: jsn is nil")
defer jsn.Close()
return LoadJSONFromReader(jsn)
}
func LoadJSONFromReader(r io.Reader) (jsnString []byte, err error) {
x.Assert(r != nil, "LoadJSONFromReader: r is nil")
jsnBytes, err := io.ReadAll(r)
if err != nil {
return nil, err
}
return jsnBytes, nil
}