Created
February 20, 2024 13:15
-
-
Save allochi/f3dbc0cf3c1b9794fe90f9b8b2af12e7 to your computer and use it in GitHub Desktop.
Script to transfer postgres `json` field to camel case
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
package main | |
import ( | |
"fmt" | |
"log" | |
"regexp" | |
"strings" | |
"github.com/jmoiron/sqlx" | |
"github.com/stoewer/go-strcase" | |
_ "github.com/lib/pq" | |
) | |
// const payload = `{"kind":"","amount":"500000000000000000000","contract":"","tokenId":"504","resources":[{"ipfs": "bafybeif4lwseqmci5nczti5wefcvfc4akmbkov5s2zr57dili6c7p4dzum", "file_type": "image/png", "description": ""}, {"ipfs": "bafkreiffheeonn4mtbjopfpa565sxvxjqqyrgztzjwe5uhpq7w7oah4lhy", "file_type": "image/png", "description": "Heres the original smartcontract of the collection"}],"blockchain":""}` | |
func main() { | |
db, err := sqlx.Connect("postgres", "user=... dbname=... sslmode=disable host=localhost") | |
if err != nil { | |
log.Fatalln(err) | |
} | |
defer db.Close() | |
if err := db.Ping(); err != nil { | |
log.Fatal(err) | |
} else { | |
log.Println("Successfully Connected") | |
} | |
rows, _ := db.Queryx("SELECT address, params FROM requests") | |
var address string | |
var params string | |
for rows.Next() { | |
err := rows.Scan(&address, ¶ms) | |
if err != nil { | |
log.Fatalln(err) | |
} | |
fmt.Printf("%s : %s\n", address, convertKeys(params)) | |
} | |
} | |
func convertKeys(payload string) string { | |
m := regexp.MustCompile(`("\w+":)`) | |
matches := m.FindAllString(payload, -1) | |
Replacements := make(map[string]string) | |
for _, match := range matches { | |
Replacements[match] = strcase.LowerCamelCase(match) | |
// fmt.Printf("Match: %s => %s\n", match, strcase.LowerCamelCase(match)) | |
} | |
result := payload | |
for k, v := range Replacements { | |
result = strings.ReplaceAll(result, k, v) | |
} | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment