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"],
"
Name :", result["name"],
"
Department :", result["department"],
"
Designation :", result["designation"],
"
Address :", address["city"], address["state"], address["country"])
}
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)
//...
// You need a struct to unmarshal file:
// After running this function with Some_struct,
// your object will be filled with json file data
func parseJsonFile(file string, obj *Some_struct) {
jsonFile, err := os.Open(file)
// if we os.Open returns an error then handle it
if err != nil {
fmt.Println(err, "| Can find a file")
} else {
fmt.Println("File found!")
}
// defer the closing of our jsonFile so that we can parse it later on
defer jsonFile.Close()
// read our opened xmlFile as a byte array.
byteValue, _ := ioutil.ReadAll(jsonFile)
// we unmarshal our byteArray which contains our
// jsonFile's content into 'users' which we defined above
json.Unmarshal(byteValue, &obj)
}