Home > Backend Development > Golang > How to Decode JSON with Embedded JSON-Encoded Strings?

How to Decode JSON with Embedded JSON-Encoded Strings?

Linda Hamilton
Release: 2024-12-16 09:59:11
Original
166 people have browsed it

How to Decode JSON with Embedded JSON-Encoded Strings?

Decoding JSON with Embedded JSON-Encoded Strings

In the context of parsing a complex JSON response from an external API, a problem arises due to the presence of JSON-encoded strings within the JSON object. The JSON structure contains a field called "text" that includes an HTML string. Upon attempting to decode this JSON using a custom type, an error is encountered.

To address this issue, a two-step decoding process is necessary:

  1. Parse the main JSON structure into a simplified type that includes the "args" field as a slice of strings.
  2. Decode each string in the "args" slice as a new JSON object using a custom type that accommodates the "text" field.
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"`
}
Copy after login

An example of decoding the provided JSON string:

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), &amp;m); err != nil {
    log.Fatal(err)
}

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

By separating the decoding of the outer JSON object and the embedded JSON string, it becomes possible to handle the nested JSON structure correctly, resolving the invalid character error.

The above is the detailed content of How to Decode JSON with Embedded JSON-Encoded Strings?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template