tablib_json.go 1.6 KB

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