Created
July 29, 2018 11:39
-
-
Save NaniteFactory/94f02da8eea0626e9bcf22e6c0f79009 to your computer and use it in GitHub Desktop.
Converting escaped forms of unicode characters in JSON into unescaped UTF-8 characters.
This file contains hidden or 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 ( | |
| "encoding/json" | |
| "fmt" | |
| "strconv" | |
| "strings" | |
| ) | |
| func _UnescapeUnicodeCharactersInJSON(_jsonRaw json.RawMessage) (json.RawMessage, error) { | |
| str, err := strconv.Unquote(strings.Replace(strconv.Quote(string(_jsonRaw)), `\\u`, `\u`, -1)) | |
| if err != nil { | |
| return nil, err | |
| } | |
| return []byte(str), nil | |
| } | |
| func main() { | |
| // Both are valid JSON. | |
| var jsonRawEscaped json.RawMessage // json raw with escaped unicode chars | |
| var jsonRawUnescaped json.RawMessage // json raw with unescaped unicode chars | |
| // '\u263a' == '☺' | |
| jsonRawEscaped = []byte(`{"HelloWorld": "\uC548\uB155, \uC138\uC0C1(\u4E16\u4E0A). \u263a"}`) // "\\u263a" | |
| jsonRawUnescaped, _ = _UnescapeUnicodeCharactersInJSON(jsonRawEscaped) // "☺" | |
| fmt.Println(string(jsonRawEscaped)) // {"HelloWorld": "\uC548\uB155, \uC138\uC0C1(\u4E16\u4E0A). \u263a"} | |
| fmt.Println(string(jsonRawUnescaped)) // {"HelloWorld": "안녕, 세상(世上). ☺"} | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment