tablib_yaml.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package tablib
  2. import "gopkg.in/yaml.v2"
  3. // LoadYAML loads a dataset from a YAML source.
  4. func LoadYAML(yamlContent []byte) (*Dataset, error) {
  5. var input []map[string]interface{}
  6. if err := yaml.Unmarshal(yamlContent, &input); err != nil {
  7. return nil, err
  8. }
  9. return internalLoadFromDict(input)
  10. }
  11. // LoadDatabookYAML loads a Databook from a YAML source.
  12. func LoadDatabookYAML(yamlContent []byte) (*Databook, error) {
  13. var input []map[string]interface{}
  14. var internalInput []map[string]interface{}
  15. if err := yaml.Unmarshal(yamlContent, &input); err != nil {
  16. return nil, err
  17. }
  18. db := NewDatabook()
  19. for _, d := range input {
  20. b, err := yaml.Marshal(d["data"])
  21. if err != nil {
  22. return nil, err
  23. }
  24. if err := yaml.Unmarshal(b, &internalInput); err != nil {
  25. return nil, err
  26. }
  27. if ds, err := internalLoadFromDict(internalInput); err == nil {
  28. db.AddSheet(d["title"].(string), ds)
  29. } else {
  30. return nil, err
  31. }
  32. }
  33. return db, nil
  34. }
  35. // YAML returns a YAML representation of the Dataset as an Exportable.
  36. func (d *Dataset) YAML() (*Exportable, error) {
  37. back := d.Dict()
  38. b, err := yaml.Marshal(back)
  39. if err != nil {
  40. return nil, err
  41. }
  42. return newExportableFromBytes(b), nil
  43. }
  44. // YAML returns a YAML representation of the Databook as an Exportable.
  45. func (d *Databook) YAML() (*Exportable, error) {
  46. y := make([]map[string]interface{}, len(d.sheets))
  47. i := 0
  48. for _, s := range d.sheets {
  49. y[i] = make(map[string]interface{})
  50. y[i]["title"] = s.title
  51. y[i]["data"] = s.dataset.Dict()
  52. i++
  53. }
  54. b, err := yaml.Marshal(y)
  55. if err != nil {
  56. return nil, err
  57. }
  58. return newExportableFromBytes(b), nil
  59. }