json parse golang code example
Example 1: golang parse json file
package main
import (
"encoding/json"
"fmt"
"os"
)
type Account struct {
Username string
Email string
Password string
}
func main() {
file, _ := os.Open("account.json")
defer file.Close()
decode := json.NewDecoder(file)
account := Account{}
err := decode.Decode(&account)
if err != nil {
fmt.Println(err)
}
fmt.Println(account)
}
Example 2: parsing json data object in golang example
package main
import (
"encoding/json"
"fmt"
)
func main() {
empJson := `{
"id": 11,
"name": "Irshad",
"department": "IT",
"designation": "Product Manager",
"address": {
"city": "Mumbai",
"state": "Maharashtra",
"country": "India"
}
}`
var result map[string]interface{}
json.Unmarshal([]byte(empJson), &result)
address := result["address"].(map[string]interface{})
fmt.Println("Id :", result["id"],
"\nName :", result["name"],
"\nDepartment :", result["department"],
"\nDesignation :", result["designation"],
"\nAddress :", address["city"], address["state"], address["country"])
}