Home >Backend Development >Golang >How to Decode a JSON String Containing Nested JSON-Encoded Strings?

How to Decode a JSON String Containing Nested JSON-Encoded Strings?

Barbara Streisand
Barbara StreisandOriginal
2024-12-06 04:08:18325browse

How to Decode a JSON String Containing Nested JSON-Encoded Strings?

Decode JSON with Included JSON-Encoded Strings

Problem

When attempting to decode a JSON string containing a nested JSON object, the application receives an error: "invalid character 'h' after object key:value pair."

Solution

The error is caused by an invalid character in the nested JSON object's value. To properly decode the JSON, it must be done in two steps:

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

// Parse input 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)
}

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

The first step decodes the outer JSON object into a main struct, which contains an array of strings. The second step loops through the array and decodes each string as a nested JSON object. This allows the application to properly parse the JSON data and avoid the error.

The above is the detailed content of How to Decode a JSON String Containing Nested 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