Skip to content

Instantly share code, notes, and snippets.

@parzibyte
Created March 21, 2019 05:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save parzibyte/b8b1189e21126f8d169cb926e99f3a76 to your computer and use it in GitHub Desktop.
Save parzibyte/b8b1189e21126f8d169cb926e99f3a76 to your computer and use it in GitHub Desktop.
package main
/*
Decodificar JSON con Go
@author parzibyte
*/
import (
"encoding/json"
"fmt"
)
func main() {
// Nota: Convertimos a []byte la cadena porque Unmarshal lo pide
nombreComoJson := []byte(`"Luis Cabrera Benito"`)
// Definir variable
var nombre string
// Decodificar. No olvides pasar LA DIRECCIÓN en lugar de la variable en sí
err := json.Unmarshal(nombreComoJson, &nombre)
if err != nil {
fmt.Printf("Error decodificando: %v\n", err)
} else {
fmt.Printf("Nombre: %s\n", nombre)
}
// Arreglo como JSON, este podría venir de un formulario, petición o lo que sea
arregloComoJson := []byte(`["Resident Evil","Super Mario Bros","Cuphead","Halo"]`)
// Debemos definir la variable que alojará los valores decodificados
arreglo := []string{}
// Y ahora decodificamos pasando el apuntador
err = json.Unmarshal(arregloComoJson, &arreglo)
if err != nil {
fmt.Printf("Error decodificando: %v\n", err)
} else {
fmt.Println("En posición 0: ", arreglo[0]) // Resident Evil
}
// Otra vez los structs
type Raza struct {
Nombre, Pais string
}
type Mascota struct {
Nombre string
Edad int
Raza Raza
Amigos []string // Arreglo de strings
}
// Vamos a probar...
mascotaComoJson := []byte(`{"Nombre":"Maggie","Edad":3,"Raza":{"Nombre":"Caniche","Pais":"Francia"},"Amigos":["Bichi","Snowball","Coqueta","Cuco","Golondrino"]}`)
// Recuerda, primero se define la variable
var mascota Mascota
// Y luego se manda su dirección de memoria
err = json.Unmarshal(mascotaComoJson, &mascota)
if err != nil {
fmt.Printf("Error decodificando: %v\n", err)
} else {
// Listo. Ahora podemos imprimir
fmt.Printf("El nombre: %s\n", mascota.Nombre)
fmt.Printf("País de Raza: %s\n", mascota.Raza.Pais)
fmt.Printf("Primer amigo: %v\n", mascota.Amigos[0])
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment