Pour encoder des données JSON dans Go, procédez comme suit : Utilisez json.Marshal pour encoder les types Go en tranches d'octets JSON. Utilisez json.Unmarshal pour décoder les types Go à partir de l'encodage JSON et stocker les tranches d'octets JSON dans les types Go.
L'encodage des données JSON dans Go est un processus simple qui peut être réalisé à l'aide de la bibliothèque standard encoding/json
. La bibliothèque fournit un riche ensemble de fonctions pour encoder les types Go en JSON et décoder les types Go à partir de l'encodage JSON. encoding/json
标准库来完成的简单明了的过程。该库提供了丰富的函数用于将 Go 类型编码为 JSON,以及从 JSON 编码中解码 Go 类型。
要将Go类型编码为JSON,可以使用 json.Marshal
函数。该函数接受一个 Go 值并返回其相应的 JSON 编码的字节切片。
package main import ( "encoding/json" "fmt" ) type User struct { Name string Age int Admin bool } func main() { user := User{Name: "John Doe", Age: 30, Admin: false} jsonBytes, err := json.Marshal(user) if err != nil { fmt.Println("Error encoding user:", err) return } fmt.Println(string(jsonBytes)) }
上面的代码片段会输出如下 JSON:
{"Name":"John Doe","Age":30,"Admin":false}
要从 JSON 编码中解码一个 Go 类型,可以使用 json.Unmarshal
json.Marshal
. Cette fonction accepte une valeur Go et renvoie sa tranche d'octets codée en JSON correspondante. package main import ( "encoding/json" "fmt" ) type User struct { Name string Age int Admin bool } func main() { jsonBytes := []byte(`{"Name":"John Doe","Age":30,"Admin":false}`) var user User if err := json.Unmarshal(jsonBytes, &user); err != nil { fmt.Println("Error decoding user:", err) return } fmt.Println(user) }
{John Doe 30 false}
json.Unmarshal
. Cette fonction accepte une tranche d'octets codée en JSON et stocke la valeur correspondante dans le type Go fourni. Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!