forked from jovemsabio/json-study
47 lines
1.5 KiB
Go
47 lines
1.5 KiB
Go
|
|
package main
|
||
|
|
|
||
|
|
import (
|
||
|
|
"encoding/json"
|
||
|
|
"fmt" // Este pacote contém funções para ecoar no terminal
|
||
|
|
"os"
|
||
|
|
)
|
||
|
|
|
||
|
|
func main() {
|
||
|
|
var dados map[string]any
|
||
|
|
|
||
|
|
data, err := os.ReadFile("arq.json")
|
||
|
|
if err != nil {
|
||
|
|
panic(err)
|
||
|
|
}
|
||
|
|
|
||
|
|
err = json.Unmarshal(data, &dados)
|
||
|
|
if err != nil {
|
||
|
|
panic(err)
|
||
|
|
}
|
||
|
|
|
||
|
|
for chave, valor := range dados {
|
||
|
|
switch v := valor.(type) {
|
||
|
|
case string:
|
||
|
|
fmt.Printf("Chave: %s (String) -> %s\n", chave, v)
|
||
|
|
case float64:
|
||
|
|
fmt.Printf("Chave: %s (Número) -> %.2f\n", chave, v)
|
||
|
|
case bool:
|
||
|
|
fmt.Printf("Chave: %s (Bool) -> %v\n", chave, v)
|
||
|
|
case []any:
|
||
|
|
fmt.Printf("Chave: %s (Array) -> \n", chave)
|
||
|
|
for i, item := range v {
|
||
|
|
fmt.Printf(" Item %d: %v\n", i, item)
|
||
|
|
}
|
||
|
|
default:
|
||
|
|
fmt.Printf("Chave: %s (Tipo desconhecido) -> %v\n", chave, v)
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
// O recurso da linha abaixo chama-se:
|
||
|
|
// type assertion (é bom estudar isso). var.(type)
|
||
|
|
var inteiro int = int(dados["integer"].(float64))
|
||
|
|
|
||
|
|
fmt.Println("Mesmo que o valor seja inteiro, json.Unmarshal() lê como int64")
|
||
|
|
fmt.Printf("Valor de integer como inteiro: %d\n", inteiro)
|
||
|
|
}
|