simplejson.go 10 KB

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