Home > Backend Development > Golang > How Can I Make Raw Unicode-Escaped JSON Data Readable in Go?

How Can I Make Raw Unicode-Escaped JSON Data Readable in Go?

DDD
Release: 2024-12-05 19:28:11
Original
687 people have browsed it

How Can I Make Raw Unicode-Escaped JSON Data Readable in Go?

How do I Make Raw Unicode Encoded Content Readable?

When requesting JSON data from a web API, you may encounter raw ASCII content that appears as Unicode escapes. While using bufio.ScanRunes to parse the response fails, decoding the response using tools like the json package or strconv.Unquote can effectively convert the Unicode escapes into readable text.

Detailed Explanation:

The JSON data provided in the question contains Unicode characters represented using backslash escapes, such as u5408 and u672a. To decode these escapes and reveal the actual Unicode characters, we can utilize the following methods:

  • JSON Package (json): JSON supports automatic decoding of Unicode escapes when unmarshaling JSON data. Here's an example:
package main

import (
    "encoding/json"
)

func main() {
    var i interface{}
    err := json.Unmarshal([]byte(`{"name": "\u5408\u80a5"}`), &i)
    fmt.Println(err, i)
}
Copy after login

Output (try it on the Go Playground):

<nil> map[name:同学]
Copy after login
  • strconv.Unquote: For unquoting smaller fragments of Unicode-encoded text, strconv.Unquote can be used. It expects a string enclosed in quotes, as shown below:
fmt.Println(strconv.Unquote(`"\u7d20\u672a\u8c0b"`))
Copy after login

Output (try it on the Go Playground):

素未谋
Copy after login

Remember that strconv.Unquote requires the string to be enclosed in quotes, achieved using a raw string literal ( ` ) to prevent the compiler from unquoting the escapes itself.

The above is the detailed content of How Can I Make Raw Unicode-Escaped JSON Data Readable in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template