Skip to content

Instantly share code, notes, and snippets.

@asafg6
Created May 4, 2021 16:19
Show Gist options
  • Save asafg6/f80bf7d13512e0f9af4030057f24c7fc to your computer and use it in GitHub Desktop.
Save asafg6/f80bf7d13512e0f9af4030057f24c7fc to your computer and use it in GitHub Desktop.
Dynamic json fields printing in Go
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