Skip to content

Commit

Permalink
Add support for JSON serialization in FromJSON function
Browse files Browse the repository at this point in the history
  • Loading branch information
chand1012 committed Feb 25, 2024
1 parent 7dd140a commit 12e4f27
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
1 change: 1 addition & 0 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@ func run(cmd *cobra.Command, args []string) {
if err != nil {
logger.HandlePanic(log, err, verbose)
}
log.Debug("Loaded file")
defer d.Close()

if columnNames {
Expand Down
17 changes: 15 additions & 2 deletions pkg/db/from_json.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package db
import (
"database/sql"
"encoding/json"
"reflect"

_ "github.com/glebarez/go-sqlite"

Expand Down Expand Up @@ -65,11 +66,23 @@ func FromJSON(b []byte, tableName string) (*sql.DB, string, error) {
var values []any
for _, column := range columns {
// if the column is not present in the record, insert a NULL
if record[column] == nil {
value := record[column]
if value == nil {
values = append(values, nil)
continue
}
values = append(values, record[column])
// Use reflect to determine if the type is a map or a slice
valType := reflect.TypeOf(value)
if valType.Kind() == reflect.Map || valType.Kind() == reflect.Slice {
// Marshal to JSON
jsonValue, err := json.Marshal(value)
if err != nil {
return nil, tempName, err
}
values = append(values, string(jsonValue))
continue // Continue to the next column after appending
}
values = append(values, value)
}
_, err = stmt.Exec(values...)
if err != nil {
Expand Down

0 comments on commit 12e4f27

Please sign in to comment.