GoDict/internal/dict/dict_serialization.go
2024-02-18 15:37:23 +03:30

109 lines
2.3 KiB
Go

package dict
import (
"encoding/json"
"os"
"gopkg.in/yaml.v3"
)
func LoadYaml(fn string) (Dict, error) {
content, err := os.ReadFile(fn)
if err != nil {
return nil, err
}
var data Dict
err = yaml.Unmarshal(content, &data)
if err != nil {
return nil, err
}
return data, nil
}
func LoadYamlStr(yamlStr string) (Dict, error) {
var data Dict
err := yaml.Unmarshal([]byte(yamlStr), &data)
if err != nil {
return nil, err
}
return data, nil
}
func (d Dict) DumpYaml(fn string) error {
data, err := yaml.Marshal(d)
if err != nil {
return err
}
return os.WriteFile(fn, data, 0644) // Write with user read/write, group read, and others read permissions
}
func (d Dict) DumpYamlStr() (string, error) {
data, err := yaml.Marshal(d)
if err != nil {
return "", err
}
return string(data), nil
}
// loadJson loads the dictionary from a JSON file.
func LoadJson(fn string) (Dict, error) {
var data Dict
content, err := os.ReadFile(fn)
if err != nil {
return nil, err
}
err = json.Unmarshal(content, &data)
if err != nil {
return nil, err
}
return data, nil
}
func LoadJsonStr(jsonStr string) (Dict, error) {
var data Dict
err := json.Unmarshal([]byte(jsonStr), &data)
if err != nil {
return nil, err
}
return data, nil
}
// dumpJson writes the dictionary to a JSON file.
func (d Dict) DumpJson(fn string) error {
data, err := json.Marshal(d)
if err != nil {
return err
}
return os.WriteFile(fn, data, 0644) // Write with user read/write, group read, and others read permissions
}
// dumpJsonIndent writes the dictionary to a JSON file but applies indent first.
func (d Dict) DumpJsonIndent(fn string, prefix, indent string) error {
data, err := json.MarshalIndent(d, prefix, indent)
if err != nil {
return err
}
return os.WriteFile(fn, data, 0644) // Write with user read/write, group read, and others read permissions
}
// dumpJsonStr returns the dictionary as a JSON string.
func (d Dict) DumpJsonStr() (string, error) {
data, err := json.Marshal(d)
if err != nil {
return "", err
}
return string(data), nil
}
// dumpJsonStr returns the dictionary as a JSON string.
func (d Dict) DumpJsonStrIndent(prefix, indent string) (string, error) {
data, err := json.MarshalIndent(d, prefix, indent)
if err != nil {
return "", err
}
return string(data), nil
}