Last active
November 27, 2020 00:29
-
-
Save madflojo/c845e14fd76ab380316b250867b9ebb0 to your computer and use it in GitHub Desktop.
map.vs.struct.safeparser
This file contains hidden or 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() { | |
// Create a map to parse the JSON | |
var data map[string]interface{} | |
// Define a JSON string | |
j := `{"name":"example","numbers":[1,2,3,4],"nested":{"isit":true,"description":"a nested json"}}` | |
// Parse our JSON string | |
err := json.Unmarshal([]byte(j), &data) | |
if err != nil { | |
fmt.Printf("Error parsing JSON string - %s", err) | |
} | |
// Print out the JSON Name | |
n, ok := data["name"].(string) | |
if !ok { | |
// set to default | |
n = "default" | |
} | |
fmt.Printf("Name is %s\n", n) | |
// Print out the JSON Numbers | |
var nums []int | |
i, ok := data["numbers"].([]interface{}) | |
if ok { | |
for _, v := range i { | |
x, ok := v.(float64) | |
if !ok { | |
// set to default | |
nums = []int{} | |
break | |
} | |
nums = append(nums, int(x)) | |
} | |
} | |
fmt.Printf("Numbers are") | |
for _, v := range nums { | |
fmt.Printf(" %d", v) | |
} | |
fmt.Printf("\n") | |
// Print out the JSON description | |
desc := "Description Not Found" | |
d, ok := data["nested"].(map[string]interface{}) | |
if ok { | |
desc, ok = d["description"].(string) | |
if !ok { | |
desc = "" | |
} | |
} | |
fmt.Printf("Description is %s", desc) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment