Skip to content

Instantly share code, notes, and snippets.

@dorneanu
Last active September 20, 2022 03:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dorneanu/1ff7e23125c55e07a0893b00768c69fa to your computer and use it in GitHub Desktop.
Save dorneanu/1ff7e23125c55e07a0893b00768c69fa to your computer and use it in GitHub Desktop.
Golang: Convert JSON string/objects to list of structure
// Go Playground: https://play.golang.org/p/cMutpCzpmth
package main
import (
"fmt"
"encoding/json"
)
// Field is a key value structure
type Field struct {
name string
value string
}
func main() {
fields := []Field{}
jsonStr := `[
{"a": "alles klar", "b": "c", "d": "1"},
{"key": "value"}
]`
data := []map[string]interface{}{}
// Convert json string to list of map[string]interface{}
err := json.Unmarshal([]byte(jsonStr), &data)
if err != nil {
panic(err)
}
for _, v := range data {
// Keys contains available keys in current map
keys := make([]string, 0, len(v))
// Copy keys
for k := range v {
keys = append(keys, k)
}
for _, key := range keys {
field := Field {
name: key,
value: fmt.Sprintf("%s", v[key].(string)),
}
fields = append(fields, field)
}
}
for _, f := range fields {
fmt.Printf("%#v\n", f)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment