xxxxxxxxxx
package main
import (
"encoding/json"
"fmt"
)
func main() {
//Simple Employee JSON object which we will parse
empJson := `{
"id": 11,
"name": "Irshad",
"department": "IT",
"designation": "Product Manager",
"address": {
"city": "Mumbai",
"state": "Maharashtra",
"country": "India"
}
}`
// Declared an empty interface
var result map[string]interface{}
// Unmarshal or Decode the JSON to the interface.
json.Unmarshal([]byte(empJson), &result)
address := result["address"].(map[string]interface{})
//Reading each value by its key
fmt.Println("Id :", result["id"],
"\nName :", result["name"],
"\nDepartment :", result["department"],
"\nDesignation :", result["designation"],
"\nAddress :", address["city"], address["state"], address["country"])
}
xxxxxxxxxx
import "encoding/json"
//...
// ...
myJsonString := `{"some":"json"}`
// `&myStoredVariable` is the address of the variable we want to store our
// parsed data in
json.Unmarshal([]byte(myJsonString), &myStoredVariable)
//...
xxxxxxxxxx
package main
import (
"encoding/json"
"fmt"
)
type User struct {
Username string `json:"username"`
Age int `json:"age"`
}
func main() {
var user User
jsonString := `{"username": "john", "age": 25}`
err := json.Unmarshal([]byte(jsonString), &user)
if err != nil {
panic(err)
}
// Output: john
fmt.Println(user.Username)
// Output: 25
fmt.Println(user.Age)
}