mirror of
https://github.com/davidallendj/magellan.git
synced 2025-12-20 03:27:03 -07:00
feat: added JSON utility functions
This commit is contained in:
parent
4dc9af8141
commit
2a1a2b4f52
1 changed files with 59 additions and 0 deletions
59
internal/util/json.go
Normal file
59
internal/util/json.go
Normal file
|
|
@ -0,0 +1,59 @@
|
||||||
|
package util
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
type JSONObject = map[string]any
|
||||||
|
type JSONArray = []any
|
||||||
|
|
||||||
|
func TidyJSON(s string) string {
|
||||||
|
s = strings.ReplaceAll(s, "\n", "")
|
||||||
|
s = strings.ReplaceAll(s, "\t", "")
|
||||||
|
s = strings.ReplaceAll(s, " ", "")
|
||||||
|
return strings.ReplaceAll(s, "\"", "'")
|
||||||
|
}
|
||||||
|
|
||||||
|
func UpdateJSON(input []byte, key string, value JSONObject) ([]byte, error) {
|
||||||
|
var (
|
||||||
|
data map[string]any
|
||||||
|
output []byte
|
||||||
|
err error
|
||||||
|
)
|
||||||
|
|
||||||
|
if json.Valid(input) {
|
||||||
|
// unmarshal input
|
||||||
|
err = json.Unmarshal(input, &data)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to unmarshal input data: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// add KV, marshal, and return
|
||||||
|
data[key] = value
|
||||||
|
output, err = json.Marshal(data)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to marshal updated data: %v", err)
|
||||||
|
}
|
||||||
|
return output, nil
|
||||||
|
} else {
|
||||||
|
return nil, fmt.Errorf("not valid json")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func FromJSON(input []byte) (JSONObject, error) {
|
||||||
|
if json.Valid(input) {
|
||||||
|
var (
|
||||||
|
obj JSONObject
|
||||||
|
err error
|
||||||
|
)
|
||||||
|
err = json.Unmarshal(input, &obj)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to unmarshal input data: %v", err)
|
||||||
|
}
|
||||||
|
return obj, nil
|
||||||
|
} else {
|
||||||
|
return nil, fmt.Errorf("not a valid JSON")
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
Add table
Add a link
Reference in a new issue