gitee.com/sy_183/go-common@v1.0.5-0.20231205030221-958cfe129b47/config.v2/json.go (about) 1 package config 2 3 import ( 4 "bytes" 5 "encoding/json" 6 "fmt" 7 "gitee.com/sy_183/go-common/yaml" 8 "io" 9 "strconv" 10 ) 11 12 type ErrUnexpectToken struct { 13 Token any 14 } 15 16 func (e ErrUnexpectToken) Error() string { 17 return fmt.Sprintf("unexpect token '%v'", e.Token) 18 } 19 20 type JsonNode yaml.Node 21 22 func (n *JsonNode) unmarshalSequence(d *json.Decoder) error { 23 n.Kind = yaml.SequenceNode 24 n.Tag = "!!seq" 25 for { 26 vt, err := d.Token() 27 if err != nil { 28 return err 29 } 30 31 if e, ok := vt.(json.Delim); ok { 32 if e == ']' { 33 return nil 34 } 35 return ErrUnexpectToken{Token: vt} 36 } 37 38 vn := new(JsonNode) 39 if err := vn.unmarshalValue(d, vt); err != nil { 40 return err 41 } 42 n.Content = append(n.Content, (*yaml.Node)(vn)) 43 } 44 } 45 46 func (n *JsonNode) unmarshalMapping(d *json.Decoder) error { 47 n.Kind = yaml.MappingNode 48 n.Tag = "!!map" 49 for { 50 kt, err := d.Token() 51 if err != nil { 52 return err 53 } 54 55 if e, ok := kt.(json.Delim); ok { 56 if e == '}' { 57 return nil 58 } 59 return ErrUnexpectToken{Token: kt} 60 } 61 62 vt, err := d.Token() 63 if err != nil { 64 return err 65 } 66 67 if key, ok := kt.(string); ok { 68 n.Content = append(n.Content, &yaml.Node{ 69 Kind: yaml.ScalarNode, 70 Tag: "!!str", 71 Value: key, 72 }) 73 vn := new(JsonNode) 74 if err := vn.unmarshalValue(d, vt); err != nil { 75 return err 76 } 77 n.Content = append(n.Content, (*yaml.Node)(vn)) 78 } else { 79 return ErrUnexpectToken{Token: kt} 80 } 81 } 82 } 83 84 func (n *JsonNode) unmarshalScalar(token any) error { 85 switch tok := token.(type) { 86 case bool: 87 n.Kind = yaml.ScalarNode 88 n.Tag = "!!bool" 89 n.Value = strconv.FormatBool(tok) 90 case json.Number: 91 n.Kind = yaml.ScalarNode 92 n.Value = string(tok) 93 case string: 94 n.Kind = yaml.ScalarNode 95 n.Tag = "!!str" 96 n.Value = tok 97 case nil: 98 n.Kind = yaml.ScalarNode 99 n.Tag = "!!null" 100 default: 101 return ErrUnexpectToken{Token: token} 102 } 103 return nil 104 } 105 106 func (n *JsonNode) unmarshalValue(d *json.Decoder, token any) error { 107 switch tok := token.(type) { 108 case json.Delim: 109 switch tok { 110 case '[': 111 return n.unmarshalSequence(d) 112 case '{': 113 return n.unmarshalMapping(d) 114 default: 115 return ErrUnexpectToken{Token: token} 116 } 117 default: 118 return n.unmarshalScalar(token) 119 } 120 } 121 122 func (n *JsonNode) UnmarshalJSON(bs []byte) error { 123 d := json.NewDecoder(bytes.NewReader(bs)) 124 d.UseNumber() 125 126 token, err := d.Token() 127 if err != nil { 128 if err == io.EOF { 129 return nil 130 } 131 return err 132 } 133 134 return n.unmarshalValue(d, token) 135 } 136 137 type JsonParser struct{} 138 139 func (p JsonParser) Parse(r io.Reader) (*yaml.Node, error) { 140 node := new(JsonNode) 141 if err := json.NewDecoder(r).Decode(node); err != nil { 142 return nil, err 143 } 144 return (*yaml.Node)(node), nil 145 }