Last active
September 20, 2022 03:27
-
-
Save dorneanu/1ff7e23125c55e07a0893b00768c69fa to your computer and use it in GitHub Desktop.
Golang: Convert JSON string/objects to list of structure
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
// 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