Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save NaniteFactory/94f02da8eea0626e9bcf22e6c0f79009 to your computer and use it in GitHub Desktop.

Select an option

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.
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