Use the following given a slice of valid database field names fieldNames
and JSON data data
:
var j map[string]interface{}
if err := json.Unmarshal(data, &j); err != nil {
// handle error
}
var names []string
var inserts []string
var values []interface{}
for _, n := range fieldNames {
if v, ok := j[n]; ok {
names = append(names, n)
inserts = append(inserts, "?")
values = append(values, v)
}
}
statement := "insert into yourTable (" +
strings.Join(names, ", ") +
") values (" + strings.Join(inserts, ", ") + ")"
err := db.Exec(statement, values...)
To avoid SQL injection attacks, it's important to work from a slice of known column names.
You can query the database to create the fieldNames
slice. See Get table column names in MySQL? for the query required.
If the column names and JSON names are different, then replace the slice with a map where the keys are the column names and the values are the JSON names:
fieldNames := map[string]string{
"column1": "json1",
... and so on
}
var j map[string]interface{}
if err := json.Unmarshal(data, &j); err != nil {
// handle error
}
var names []string
var inserts []string
var values []interface{}
for dbName, jsonName := range fieldNames {
if v, ok := j[jsonName]; ok {
names = append(names, dbName)
inserts = append(inserts, "?")
values = append(values, v)
}
}
statement := "insert into yourTable (" +
strings.Join(names, ", ") +
") values (" + strings.Join(inserts, ", ") + ")"
err := db.Exec(statement, values...)