simplejson.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. package simplejson
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "log"
  8. )
  9. // returns the current implementation version
  10. func Version() string {
  11. return "0.5.0"
  12. }
  13. type Json struct {
  14. data interface{}
  15. }
  16. func (j *Json) FromDB(data []byte) error {
  17. j.data = make(map[string]interface{})
  18. dec := json.NewDecoder(bytes.NewBuffer(data))
  19. dec.UseNumber()
  20. return dec.Decode(&j.data)
  21. }
  22. func (j *Json) ToDB() ([]byte, error) {
  23. if j == nil || j.data == nil {
  24. return nil, nil
  25. }
  26. return j.Encode()
  27. }
  28. // NewJson returns a pointer to a new `Json` object
  29. // after unmarshaling `body` bytes
  30. func NewJson(body []byte) (*Json, error) {
  31. j := new(Json)
  32. err := j.UnmarshalJSON(body)
  33. if err != nil {
  34. return nil, err
  35. }
  36. return j, nil
  37. }
  38. // New returns a pointer to a new, empty `Json` object
  39. func New() *Json {
  40. return &Json{
  41. data: make(map[string]interface{}),
  42. }
  43. }
  44. // Interface returns the underlying data
  45. func (j *Json) Interface() interface{} {
  46. return j.data
  47. }
  48. // Encode returns its marshaled data as `[]byte`
  49. func (j *Json) Encode() ([]byte, error) {
  50. return j.MarshalJSON()
  51. }
  52. // EncodePretty returns its marshaled data as `[]byte` with indentation
  53. func (j *Json) EncodePretty() ([]byte, error) {
  54. return json.MarshalIndent(&j.data, "", " ")
  55. }
  56. // Implements the json.Marshaler interface.
  57. func (j *Json) MarshalJSON() ([]byte, error) {
  58. fmt.Printf("MarshalJSON")
  59. return json.Marshal(&j.data)
  60. }
  61. // Set modifies `Json` map by `key` and `value`
  62. // Useful for changing single key/value in a `Json` object easily.
  63. func (j *Json) Set(key string, val interface{}) {
  64. m, err := j.Map()
  65. if err != nil {
  66. return
  67. }
  68. m[key] = val
  69. }
  70. // SetPath modifies `Json`, recursively checking/creating map keys for the supplied path,
  71. // and then finally writing in the value
  72. func (j *Json) SetPath(branch []string, val interface{}) {
  73. if len(branch) == 0 {
  74. j.data = val
  75. return
  76. }
  77. // in order to insert our branch, we need map[string]interface{}
  78. if _, ok := (j.data).(map[string]interface{}); !ok {
  79. // have to replace with something suitable
  80. j.data = make(map[string]interface{})
  81. }
  82. curr := j.data.(map[string]interface{})
  83. for i := 0; i < len(branch)-1; i++ {
  84. b := branch[i]
  85. // key exists?
  86. if _, ok := curr[b]; !ok {
  87. n := make(map[string]interface{})
  88. curr[b] = n
  89. curr = n
  90. continue
  91. }
  92. // make sure the value is the right sort of thing
  93. if _, ok := curr[b].(map[string]interface{}); !ok {
  94. // have to replace with something suitable
  95. n := make(map[string]interface{})
  96. curr[b] = n
  97. }
  98. curr = curr[b].(map[string]interface{})
  99. }
  100. // add remaining k/v
  101. curr[branch[len(branch)-1]] = val
  102. }
  103. // Del modifies `Json` map by deleting `key` if it is present.
  104. func (j *Json) Del(key string) {
  105. m, err := j.Map()
  106. if err != nil {
  107. return
  108. }
  109. delete(m, key)
  110. }
  111. // Get returns a pointer to a new `Json` object
  112. // for `key` in its `map` representation
  113. //
  114. // useful for chaining operations (to traverse a nested JSON):
  115. // js.Get("top_level").Get("dict").Get("value").Int()
  116. func (j *Json) Get(key string) *Json {
  117. m, err := j.Map()
  118. if err == nil {
  119. if val, ok := m[key]; ok {
  120. return &Json{val}
  121. }
  122. }
  123. return &Json{nil}
  124. }
  125. // GetPath searches for the item as specified by the branch
  126. // without the need to deep dive using Get()'s.
  127. //
  128. // js.GetPath("top_level", "dict")
  129. func (j *Json) GetPath(branch ...string) *Json {
  130. jin := j
  131. for _, p := range branch {
  132. jin = jin.Get(p)
  133. }
  134. return jin
  135. }
  136. // GetIndex returns a pointer to a new `Json` object
  137. // for `index` in its `array` representation
  138. //
  139. // this is the analog to Get when accessing elements of
  140. // a json array instead of a json object:
  141. // js.Get("top_level").Get("array").GetIndex(1).Get("key").Int()
  142. func (j *Json) GetIndex(index int) *Json {
  143. a, err := j.Array()
  144. if err == nil {
  145. if len(a) > index {
  146. return &Json{a[index]}
  147. }
  148. }
  149. return &Json{nil}
  150. }
  151. // CheckGet returns a pointer to a new `Json` object and
  152. // a `bool` identifying success or failure
  153. //
  154. // useful for chained operations when success is important:
  155. // if data, ok := js.Get("top_level").CheckGet("inner"); ok {
  156. // log.Println(data)
  157. // }
  158. func (j *Json) CheckGet(key string) (*Json, bool) {
  159. m, err := j.Map()
  160. if err == nil {
  161. if val, ok := m[key]; ok {
  162. return &Json{val}, true
  163. }
  164. }
  165. return nil, false
  166. }
  167. // Map type asserts to `map`
  168. func (j *Json) Map() (map[string]interface{}, error) {
  169. if m, ok := (j.data).(map[string]interface{}); ok {
  170. return m, nil
  171. }
  172. return nil, errors.New("type assertion to map[string]interface{} failed")
  173. }
  174. // Array type asserts to an `array`
  175. func (j *Json) Array() ([]interface{}, error) {
  176. if a, ok := (j.data).([]interface{}); ok {
  177. return a, nil
  178. }
  179. return nil, errors.New("type assertion to []interface{} failed")
  180. }
  181. // Bool type asserts to `bool`
  182. func (j *Json) Bool() (bool, error) {
  183. if s, ok := (j.data).(bool); ok {
  184. return s, nil
  185. }
  186. return false, errors.New("type assertion to bool failed")
  187. }
  188. // String type asserts to `string`
  189. func (j *Json) String() (string, error) {
  190. if s, ok := (j.data).(string); ok {
  191. return s, nil
  192. }
  193. return "", errors.New("type assertion to string failed")
  194. }
  195. // Bytes type asserts to `[]byte`
  196. func (j *Json) Bytes() ([]byte, error) {
  197. if s, ok := (j.data).(string); ok {
  198. return []byte(s), nil
  199. }
  200. return nil, errors.New("type assertion to []byte failed")
  201. }
  202. // StringArray type asserts to an `array` of `string`
  203. func (j *Json) StringArray() ([]string, error) {
  204. arr, err := j.Array()
  205. if err != nil {
  206. return nil, err
  207. }
  208. retArr := make([]string, 0, len(arr))
  209. for _, a := range arr {
  210. if a == nil {
  211. retArr = append(retArr, "")
  212. continue
  213. }
  214. s, ok := a.(string)
  215. if !ok {
  216. return nil, err
  217. }
  218. retArr = append(retArr, s)
  219. }
  220. return retArr, nil
  221. }
  222. // MustArray guarantees the return of a `[]interface{}` (with optional default)
  223. //
  224. // useful when you want to interate over array values in a succinct manner:
  225. // for i, v := range js.Get("results").MustArray() {
  226. // fmt.Println(i, v)
  227. // }
  228. func (j *Json) MustArray(args ...[]interface{}) []interface{} {
  229. var def []interface{}
  230. switch len(args) {
  231. case 0:
  232. case 1:
  233. def = args[0]
  234. default:
  235. log.Panicf("MustArray() received too many arguments %d", len(args))
  236. }
  237. a, err := j.Array()
  238. if err == nil {
  239. return a
  240. }
  241. return def
  242. }
  243. // MustMap guarantees the return of a `map[string]interface{}` (with optional default)
  244. //
  245. // useful when you want to interate over map values in a succinct manner:
  246. // for k, v := range js.Get("dictionary").MustMap() {
  247. // fmt.Println(k, v)
  248. // }
  249. func (j *Json) MustMap(args ...map[string]interface{}) map[string]interface{} {
  250. var def map[string]interface{}
  251. switch len(args) {
  252. case 0:
  253. case 1:
  254. def = args[0]
  255. default:
  256. log.Panicf("MustMap() received too many arguments %d", len(args))
  257. }
  258. a, err := j.Map()
  259. if err == nil {
  260. return a
  261. }
  262. return def
  263. }
  264. // MustString guarantees the return of a `string` (with optional default)
  265. //
  266. // useful when you explicitly want a `string` in a single value return context:
  267. // myFunc(js.Get("param1").MustString(), js.Get("optional_param").MustString("my_default"))
  268. func (j *Json) MustString(args ...string) string {
  269. var def string
  270. switch len(args) {
  271. case 0:
  272. case 1:
  273. def = args[0]
  274. default:
  275. log.Panicf("MustString() received too many arguments %d", len(args))
  276. }
  277. s, err := j.String()
  278. if err == nil {
  279. return s
  280. }
  281. return def
  282. }
  283. // MustStringArray guarantees the return of a `[]string` (with optional default)
  284. //
  285. // useful when you want to interate over array values in a succinct manner:
  286. // for i, s := range js.Get("results").MustStringArray() {
  287. // fmt.Println(i, s)
  288. // }
  289. func (j *Json) MustStringArray(args ...[]string) []string {
  290. var def []string
  291. switch len(args) {
  292. case 0:
  293. case 1:
  294. def = args[0]
  295. default:
  296. log.Panicf("MustStringArray() received too many arguments %d", len(args))
  297. }
  298. a, err := j.StringArray()
  299. if err == nil {
  300. return a
  301. }
  302. return def
  303. }
  304. // MustInt guarantees the return of an `int` (with optional default)
  305. //
  306. // useful when you explicitly want an `int` in a single value return context:
  307. // myFunc(js.Get("param1").MustInt(), js.Get("optional_param").MustInt(5150))
  308. func (j *Json) MustInt(args ...int) int {
  309. var def int
  310. switch len(args) {
  311. case 0:
  312. case 1:
  313. def = args[0]
  314. default:
  315. log.Panicf("MustInt() received too many arguments %d", len(args))
  316. }
  317. i, err := j.Int()
  318. if err == nil {
  319. return i
  320. }
  321. return def
  322. }
  323. // MustFloat64 guarantees the return of a `float64` (with optional default)
  324. //
  325. // useful when you explicitly want a `float64` in a single value return context:
  326. // myFunc(js.Get("param1").MustFloat64(), js.Get("optional_param").MustFloat64(5.150))
  327. func (j *Json) MustFloat64(args ...float64) float64 {
  328. var def float64
  329. switch len(args) {
  330. case 0:
  331. case 1:
  332. def = args[0]
  333. default:
  334. log.Panicf("MustFloat64() received too many arguments %d", len(args))
  335. }
  336. f, err := j.Float64()
  337. if err == nil {
  338. return f
  339. }
  340. return def
  341. }
  342. // MustBool guarantees the return of a `bool` (with optional default)
  343. //
  344. // useful when you explicitly want a `bool` in a single value return context:
  345. // myFunc(js.Get("param1").MustBool(), js.Get("optional_param").MustBool(true))
  346. func (j *Json) MustBool(args ...bool) bool {
  347. var def bool
  348. switch len(args) {
  349. case 0:
  350. case 1:
  351. def = args[0]
  352. default:
  353. log.Panicf("MustBool() received too many arguments %d", len(args))
  354. }
  355. b, err := j.Bool()
  356. if err == nil {
  357. return b
  358. }
  359. return def
  360. }
  361. // MustInt64 guarantees the return of an `int64` (with optional default)
  362. //
  363. // useful when you explicitly want an `int64` in a single value return context:
  364. // myFunc(js.Get("param1").MustInt64(), js.Get("optional_param").MustInt64(5150))
  365. func (j *Json) MustInt64(args ...int64) int64 {
  366. var def int64
  367. switch len(args) {
  368. case 0:
  369. case 1:
  370. def = args[0]
  371. default:
  372. log.Panicf("MustInt64() received too many arguments %d", len(args))
  373. }
  374. i, err := j.Int64()
  375. if err == nil {
  376. return i
  377. }
  378. return def
  379. }
  380. // MustUInt64 guarantees the return of an `uint64` (with optional default)
  381. //
  382. // useful when you explicitly want an `uint64` in a single value return context:
  383. // myFunc(js.Get("param1").MustUint64(), js.Get("optional_param").MustUint64(5150))
  384. func (j *Json) MustUint64(args ...uint64) uint64 {
  385. var def uint64
  386. switch len(args) {
  387. case 0:
  388. case 1:
  389. def = args[0]
  390. default:
  391. log.Panicf("MustUint64() received too many arguments %d", len(args))
  392. }
  393. i, err := j.Uint64()
  394. if err == nil {
  395. return i
  396. }
  397. return def
  398. }