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:
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"` }
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), &m); err != nil { log.Fatal(err) } var args arg if err := json.Unmarshal([]byte(m.Args[0]), &args); err != nil { log.Fatal(err) }
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!