cmd-zet/internal/lib/json.go

48 lines
763 B
Go

package lib
import (
"encoding/json"
"fmt"
"regexp"
"strconv"
"strings"
)
var ansiRegex = regexp.MustCompile(`\x1b\[[0-9;]*m`)
type Item struct {
ID int `json:"id"`
Title string `json:"title"`
}
func AsJSON(zets []string) (string, error) {
var items []Item
for _, entry := range zets {
cleanEntry := stripANSI(entry)
parts := strings.SplitN(cleanEntry, " ", 2)
id, _ := strconv.Atoi(parts[0])
item := Item{
ID: id,
Title: parts[1],
}
items = append(items, item)
}
jsonData, err := json.MarshalIndent(items, "", " ")
if err != nil {
fmt.Println("Error marshaling to JSON:", err)
return "", err
}
return string(jsonData), nil
}
func stripANSI(s string) string {
return ansiRegex.ReplaceAllString(s, "")
}