This repository has been archived on 2025-09-14. You can view files and clone it, but cannot push or open issues or pull requests.
Files
modikai-dtool/utils/output_utils.go

45 lines
844 B
Go
Raw Permalink Normal View History

2023-06-16 18:55:18 +08:00
package utils
import (
"encoding/json"
"fmt"
2023-08-03 15:25:17 +08:00
"os"
2023-06-16 18:55:18 +08:00
)
2023-08-03 15:25:17 +08:00
func ToJSON(data interface{}, indent string) (string, error) {
var jsonbyte []byte
var err error
if indent == "" {
jsonbyte, err = json.Marshal(data)
} else {
jsonbyte, err = json.MarshalIndent(data, "", indent)
2023-06-16 18:55:18 +08:00
}
2023-08-03 15:25:17 +08:00
return string(jsonbyte), err
}
func WriteFileLine(filename string, data string) error {
2023-06-26 15:58:04 +08:00
if filename == "-" {
2023-08-03 15:25:17 +08:00
fmt.Println(data)
2023-06-26 15:58:04 +08:00
} else {
2023-08-03 15:25:17 +08:00
err := os.WriteFile(filename, []byte(data), 0666)
2023-06-26 15:58:04 +08:00
if err != nil {
return err
}
}
return nil
2023-06-16 18:55:18 +08:00
}
2023-08-03 15:25:17 +08:00
func OutputJSON(data interface{}, filename string, indent string) error {
str, err := ToJSON(data, indent)
if err != nil {
fmt.Printf("Error encoding JSON: %s", err)
return err
}
err = WriteFileLine(filename, str)
if err != nil {
fmt.Printf("Error writing to file: %s", err)
return err
}
return nil
}