Created
May 4, 2021 16:19
-
-
Save asafg6/f80bf7d13512e0f9af4030057f24c7fc to your computer and use it in GitHub Desktop.
Dynamic json fields printing in Go
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" | |
"os" | |
) | |
func main() { | |
jsonString := ` | |
{ | |
"properties": { | |
"MessageId": "ididid", | |
"MessageType": "message", | |
"some_var": 1 | |
} | |
} | |
` | |
var dynamic map[string]interface{} | |
err := json.Unmarshal([]byte(jsonString), &dynamic) | |
if err != nil { | |
fmt.Println("Error: ", err) | |
os.Exit(1) | |
} | |
printMap(dynamic) | |
} | |
func printMap(m map[string]interface{}) { | |
for k, v := range m { | |
fmt.Println("Key: ", k) | |
switch v.(type) { | |
case string: | |
fmt.Println("Value is a string ", v.(string)) | |
case int: | |
fmt.Println("Value is an int ", v.(int)) | |
case map[string]interface{}: | |
printMap(v.(map[string]interface{})) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment