You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

json.go 946B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. package testfixtures
  2. import (
  3. "database/sql/driver"
  4. "encoding/json"
  5. )
  6. var (
  7. _ driver.Valuer = jsonArray{}
  8. _ driver.Valuer = jsonMap{}
  9. )
  10. type jsonArray []interface{}
  11. func (a jsonArray) Value() (driver.Value, error) {
  12. return json.Marshal(a)
  13. }
  14. type jsonMap map[string]interface{}
  15. func (m jsonMap) Value() (driver.Value, error) {
  16. return json.Marshal(m)
  17. }
  18. // Go refuses to convert map[interface{}]interface{} to JSON because JSON only support string keys
  19. // So it's necessary to recursively convert all map[interface]interface{} to map[string]interface{}
  20. func recursiveToJSON(v interface{}) (r interface{}) {
  21. switch v := v.(type) {
  22. case []interface{}:
  23. for i, e := range v {
  24. v[i] = recursiveToJSON(e)
  25. }
  26. r = jsonArray(v)
  27. case map[interface{}]interface{}:
  28. newMap := make(map[string]interface{}, len(v))
  29. for k, e := range v {
  30. newMap[k.(string)] = recursiveToJSON(e)
  31. }
  32. r = jsonMap(newMap)
  33. default:
  34. r = v
  35. }
  36. return
  37. }