github.com/sagernet/sing@v0.4.0-beta.19.0.20240518125136-f67a0988a636/common/json/badjson/json.go (about) 1 package badjson 2 3 import ( 4 "bytes" 5 6 E "github.com/sagernet/sing/common/exceptions" 7 "github.com/sagernet/sing/common/json" 8 ) 9 10 func Decode(content []byte) (any, error) { 11 decoder := json.NewDecoder(bytes.NewReader(content)) 12 return decodeJSON(decoder) 13 } 14 15 func decodeJSON(decoder *json.Decoder) (any, error) { 16 rawToken, err := decoder.Token() 17 if err != nil { 18 return nil, err 19 } 20 switch token := rawToken.(type) { 21 case json.Delim: 22 switch token { 23 case '{': 24 var object JSONObject 25 err = object.decodeJSON(decoder) 26 if err != nil { 27 return nil, err 28 } 29 rawToken, err = decoder.Token() 30 if err != nil { 31 return nil, err 32 } else if rawToken != json.Delim('}') { 33 return nil, E.New("excepted object end, but got ", rawToken) 34 } 35 return &object, nil 36 case '[': 37 var array JSONArray 38 err = array.decodeJSON(decoder) 39 if err != nil { 40 return nil, err 41 } 42 rawToken, err = decoder.Token() 43 if err != nil { 44 return nil, err 45 } else if rawToken != json.Delim(']') { 46 return nil, E.New("excepted array end, but got ", rawToken) 47 } 48 return array, nil 49 default: 50 return nil, E.New("excepted object or array end: ", token) 51 } 52 } 53 return rawToken, nil 54 }