json.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package common
  2. import (
  3. "encoding/json"
  4. "io/ioutil"
  5. "os"
  6. )
  7. type ReadData struct {
  8. Data interface{} `json:"data"`
  9. }
  10. type BaseModel struct {
  11. LaboratoryId int `json:"laboratory_id"` // 实验室ID
  12. LaboratoryName string `json:"laboratory_name"` // 实验室名称
  13. }
  14. // DeviceStatistics 实验设备使用数据
  15. type DeviceStatistics struct {
  16. BaseModel
  17. BaseEquipment int `json:"base_equipment"` // 基础科研设备
  18. LaboratoryEquipment int `json:"laboratory_equipment"` // 实验室设备
  19. UseTime int `json:"use_time"` // 使用时长
  20. ExperimentalData int `json:"experimental_data"` // 实验数据
  21. }
  22. // ReadJson 从配置文件中读取json
  23. func ReadJson(entity interface{}, path ...string) error {
  24. jPath := "data1.json"
  25. if len(path) > 0 {
  26. jPath = path[0]
  27. }
  28. // 打开json文件
  29. jsonFile, err := os.Open(jPath)
  30. if err != nil {
  31. return err
  32. }
  33. var rdata ReadData
  34. rdata.Data = &entity
  35. // 要记得关闭
  36. defer jsonFile.Close()
  37. byteValue, err := ioutil.ReadAll(jsonFile)
  38. if err != nil {
  39. return err
  40. }
  41. err = json.Unmarshal([]byte(byteValue), &rdata)
  42. if err != nil {
  43. return err
  44. }
  45. return nil
  46. }