109 lines
2.3 KiB
Go
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
|
|
}
|