From 12e4f27eeb063862c7b64431d7808f5ba6bc86a5 Mon Sep 17 00:00:00 2001 From: chand1012 Date: Sun, 25 Feb 2024 14:47:51 -0500 Subject: [PATCH] Add support for JSON serialization in FromJSON function --- cmd/root.go | 1 + pkg/db/from_json.go | 17 +++++++++++++++-- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/cmd/root.go b/cmd/root.go index 7f67686..59f491e 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -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 { diff --git a/pkg/db/from_json.go b/pkg/db/from_json.go index 5e4fdaa..cb80bc3 100644 --- a/pkg/db/from_json.go +++ b/pkg/db/from_json.go @@ -3,6 +3,7 @@ package db import ( "database/sql" "encoding/json" + "reflect" _ "github.com/glebarez/go-sqlite" @@ -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 {