forked from jovemsabio/json-study
First commit with the code
This commit is contained in:
@@ -8,6 +8,8 @@
|
|||||||
*.dll
|
*.dll
|
||||||
*.so
|
*.so
|
||||||
*.dylib
|
*.dylib
|
||||||
|
main
|
||||||
|
json-study
|
||||||
|
|
||||||
# Test binary, built with `go test -c`
|
# Test binary, built with `go test -c`
|
||||||
*.test
|
*.test
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
{
|
||||||
|
"name":"Project JSON",
|
||||||
|
"number": 5.43,
|
||||||
|
"integer": 7,
|
||||||
|
"objs": [
|
||||||
|
{
|
||||||
|
"id": 1,
|
||||||
|
"name":"Nome 1"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 2,
|
||||||
|
"name":"Nome 2"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
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)
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user