Return zets as JSON if --json or -j is passed

This commit is contained in:
Oliver Davies 2025-09-30 18:00:00 +01:00
parent 035d575f0e
commit 329d6d34e0
4 changed files with 88 additions and 4 deletions

48
internal/lib/json.go Normal file
View file

@ -0,0 +1,48 @@
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, "")
}