github.com/inazumav/sing-box@v0.0.0-20230926072359-ab51429a14f1/common/badjson/json.go (about) 1 package badjson 2 3 import ( 4 "bytes" 5 6 "github.com/inazumav/sing-box/common/json" 7 E "github.com/sagernet/sing/common/exceptions" 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 }