simplejson.go 10 KB

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