Home >Backend Development >Golang >How to Decode Nested JSON-Encoded Strings in Go?

How to Decode Nested JSON-Encoded Strings in Go?

Susan Sarandon
Susan SarandonOriginal
2024-12-05 08:12:13424browse

How to Decode Nested JSON-Encoded Strings in Go?

Decoding JSON with Nested Encoded Strings

In the provided scenario, WebSocket information is received in the form of a JSON response that includes nested JSON-encoded strings. The goal is to decode this JSON into a custom Go data structure.

The initial attempt at decoding fails due to an invalid character within the "text" field of the nested JSON string. This is because the value contains HTML markup, which is not valid JSON syntax.

Two-Step Decoding

To overcome this issue, the decoding process needs to be done in two steps:

  1. Decode the outer JSON response into a data structure that includes a slice of strings for the "args" field.
  2. Loop over the "args" slice and decode each individual string as JSON.

Code Example

Here's an updated code snippet that implements this two-step decoding process:

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"`
}

str := `{"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}}"]}`

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

for _, argStr := range m.Args {
    var args arg
    if err := json.Unmarshal([]byte(argStr), &args); err != nil {
        log.Fatal(err)
    }
    fmt.Println(args)
}

This code demonstrates the nested decoding process, allowing the application to extract the desired data from the JSON response containing encoded strings.

The above is the detailed content of How to Decode Nested JSON-Encoded Strings in Go?. 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