github.com/sandwich-go/boost@v1.3.29/xstrings/json.go (about) 1 package xstrings 2 3 import "encoding/json" 4 5 // UglyJSON removes insignificant space characters from the input json byte slice 6 // and returns the compacted result. 7 func UglyJSON(json []byte) []byte { 8 buf := make([]byte, 0, len(json)) 9 return ugly(buf, json) 10 } 11 12 func ugly(dst, src []byte) []byte { 13 dst = dst[:0] 14 for i := 0; i < len(src); i++ { 15 if src[i] > ' ' { 16 dst = append(dst, src[i]) 17 if src[i] == '"' { 18 for i = i + 1; i < len(src); i++ { 19 dst = append(dst, src[i]) 20 if src[i] == '"' { 21 j := i - 1 22 for ; ; j-- { 23 if src[j] != '\\' { 24 break 25 } 26 } 27 if (j-i)%2 != 0 { 28 break 29 } 30 } 31 } 32 } 33 } 34 } 35 return dst 36 } 37 38 // ValidJSON 是否为合法json字符串 39 func ValidJSON(bb []byte) bool { 40 if len(bb) == 0 { 41 return true 42 } 43 var jsonStr interface{} 44 err := json.Unmarshal(bb, &jsonStr) 45 return err == nil 46 }