Created
December 27, 2017 09:42
-
-
Save cloverstd/bd7d792fb85c3b2f78e2183be6a34097 to your computer and use it in GitHub Desktop.
convert []byte to ascii
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"strconv" | |
) | |
func main() { | |
// a := map[string]interface{}{ | |
// "中文": map[string]interface{}{ | |
// "test\"": "aaa中文aaa", | |
// }, | |
// "aaa": []string{ | |
// "中文", "english", | |
// }, | |
// } | |
// b, _ := json.Marshal(a) | |
b := []byte(` | |
{ | |
"code": 200, | |
"data": { | |
"user_name": "测试\'用\"户" | |
}, | |
"中文": ["中文"], | |
"message": "ok", | |
} | |
`) | |
var bb []byte | |
var start bool | |
buffer := make([]byte, 0, 1024) | |
for i := range b { | |
if b[i] == '"' { | |
if start && i != 0 { | |
// check escape | |
if b[i-1] != '\\' { | |
// end | |
s := strconv.QuoteToASCII(string(buffer)) | |
bbb := []byte(s) | |
if len(bbb) > 0 { | |
bbb = bbb[1:] | |
bb = append(bb, bbb...) | |
buffer = buffer[0:0] | |
} | |
start = false | |
continue | |
} | |
} else { | |
start = true | |
bb = append(bb, b[i]) | |
continue | |
} | |
} | |
if start { | |
buffer = append(buffer, b[i]) | |
} else { | |
bb = append(bb, b[i]) | |
} | |
} | |
fmt.Println(string(bb)) | |
fmt.Println(string(b)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment