Created
September 6, 2018 05:19
-
-
Save Ashkanph/98a32557f42997a72cd513c04967cc2e to your computer and use it in GitHub Desktop.
Unscape unicode characters in json
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
// https://stackoverflow.com/questions/28595664/how-to-stop-json-marshal-from-escaping-and#answer-51578927 | |
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