Forked from XI4222-Irshad/Embedded_Object_In_JSON_Array_Parsing.go
Created
September 1, 2020 12:18
-
-
Save vikasavnish/6264ba0cdd7812e841db616b7df0e791 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
) | |
func main() { | |
//Simple Employee JSON object which we will parse | |
empArray := `[ | |
{ | |
"id": 1, | |
"name": "Mr. Boss", | |
"department": "", | |
"designation": "Director", | |
"address": { | |
"city": "Mumbai", | |
"state": "Maharashtra", | |
"country": "India" | |
} | |
}, | |
{ | |
"id": 11, | |
"name": "Irshad", | |
"department": "IT", | |
"designation": "Product Manager", | |
"address": { | |
"city": "Mumbai", | |
"state": "Maharashtra", | |
"country": "India" | |
} | |
}, | |
{ | |
"id": 12, | |
"name": "Pankaj", | |
"department": "IT", | |
"designation": "Team Lead", | |
"address": { | |
"city": "Pune", | |
"state": "Maharashtra", | |
"country": "India" | |
} | |
} | |
]` | |
// Declared an empty interface of type Array | |
var results []map[string]interface{} | |
// Unmarshal or Decode the JSON to the interface. | |
json.Unmarshal([]byte(empArray), &results) | |
for key, result := range results { | |
address := result["address"].(map[string]interface{}) | |
fmt.Println("Reading Value for Key :", key) | |
//Reading each value by its key | |
fmt.Println("Id :", result["id"], | |
"- Name :", result["name"], | |
"- Department :", result["department"], | |
"- Designation :", result["designation"]) | |
fmt.Println("Address :", address["city"], address["state"], address["country"]) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment