// +build ignore package main import ( "encoding/base64" "encoding/json" "fmt" "github.com/btwiuse/pretty" ) func main() { str := "魑魅魍魉" buf := []byte(str) fmt.Println("str:", str) fmt.Println("str len:", len(str)) fmt.Println("buf len:", len(buf)) for i := 0; i <= len(buf); i++ { var raw json.RawMessage = buf[:i] rawbuf, _ := raw.MarshalJSON() rawstr := string(rawbuf) fmt.Printf("buf[:%d]: %q %q\n", i, string(buf[:i]), base64.StdEncoding.EncodeToString(buf[:i])) fmt.Printf("buf[:%d]: %q\n", i, rawstr) fmt.Printf("buf[:%d]: %s\n", i, pretty.JsonString(string(buf[:i]))) //fmt.Printf("buf[:%d]: %q\n", i, js(raw)) fmt.Printf("buf[:%d]: %q\n", i, pretty.JsonString(raw)) fmt.Printf("buf[:%d]: %q\n", i, pretty.JsonString(pretty.JsonString(raw))) } } func js(v interface{}) string { var ( b []byte err error ) switch v.(type) { case *json.RawMessage: b, err = v.(*json.RawMessage).MarshalJSON() case json.RawMessage: b, err = v.(json.RawMessage).MarshalJSON() default: b, err = json.Marshal(v) } if err != nil { panic(err) } return string(b) }