Home >Backend Development >Golang >How to Decode JSON Data Containing JSON-Encoded Strings?

How to Decode JSON Data Containing JSON-Encoded Strings?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-03 09:46:11868browse

How to Decode JSON Data Containing JSON-Encoded Strings?

Decoding JSON Including JSON-Encoded Strings

When receiving JSON data from external sources, it's common to encounter JSON that includes encoded JSON strings. Handling this scenario requires a two-step decoding process.

Consider the following JSON:

{"name":"message","args":["{\"method\":\"chatMsg\",\"params\":{\"channel\":\"channel\",\"name\":\"name\",\"nameColor\":\"B5B11E\",\"text\":\"<a href=\"https://play.spotify.com/browse\" target=\"_blank\">https://play.spotify.com/browse</a>\",\"time\":1455397119}}"]}

To decode this properly, we define the following structures:

type main struct {
  Name string   `json:"name"`
  Args []string `json:"args"`
}

type arg struct {
  Method string `json:"method"`
  Params par    `json:"params"`
}
type par struct {
  Channel   string `json:"channel,omitempty"`
  Name      string `json:"name,omitempty"`
  NameColor string `json:"nameColor,omitempty"`
  Text      string `json:"text,omitempty"`
  Time      int64  `json:"time,omitempty"`
}

The first step is to decode the outermost layer:

var m main
if err := json.Unmarshal([]byte(str), &amp;m); err != nil {
    log.Fatal(err)
}

Next, we decode the JSON-encoded string in the "args" array:

var args arg
if err := json.Unmarshal([]byte(m.Args[0]), &amp;args); err != nil {
    log.Fatal(err)
}

Using this two-step approach ensures that the application correctly parses both the outermost JSON and the embedded JSON strings.

The above is the detailed content of How to Decode JSON Data Containing JSON-Encoded Strings?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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