json.go 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. /*
  2. Copyright (c) 2012, Jason Moiron
  3. Permission is hereby granted, free of charge, to any person
  4. obtaining a copy of this software and associated documentation
  5. files (the "Software"), to deal in the Software without
  6. restriction, including without limitation the rights to use,
  7. copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the
  9. Software is furnished to do so, subject to the following
  10. conditions:
  11. The above copyright notice and this permission notice shall be
  12. included in all copies or substantial portions of the Software.
  13. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  14. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  15. OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  16. NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  17. HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  18. WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  20. OTHER DEALINGS IN THE SOFTWARE.
  21. // */
  22. // https://github.com/jmoiron/jsonq
  23. package myth
  24. import (
  25. "bytes"
  26. "encoding/json"
  27. "fmt"
  28. "strconv"
  29. )
  30. // JSONQuery is an object that enables querying of a Go map with a simple
  31. // positional query language.
  32. type JSONQuery struct {
  33. data map[string]interface{}
  34. }
  35. // NewJSONQuery creates a new JSONQuery obj from []byte.
  36. func NewJSONQuery(data []byte) (jq *JSONQuery, err error) {
  37. obj := make(map[string]interface{})
  38. // bytes.NewReader(data) strings.NewReader(jsonstring)
  39. dec := json.NewDecoder(bytes.NewReader(data))
  40. err = dec.Decode(&obj)
  41. if err != nil {
  42. return
  43. }
  44. jq = new(JSONQuery)
  45. jq.data = obj
  46. return
  47. }
  48. // Bool extracts a bool the JSONQuery
  49. func (jq *JSONQuery) Bool(s ...string) (bool, error) {
  50. val, err := rquery(jq.data, s...)
  51. if err != nil {
  52. return false, err
  53. }
  54. return boolFromInterface(val)
  55. }
  56. // Float extracts a float from the JsonQuery
  57. func (jq *JSONQuery) Float(s ...string) (float64, error) {
  58. val, err := rquery(jq.data, s...)
  59. if err != nil {
  60. return 0.0, err
  61. }
  62. return floatFromInterface(val)
  63. }
  64. // Int extracts an int from the JsonQuery
  65. func (jq *JSONQuery) Int(s ...string) (int, error) {
  66. val, err := rquery(jq.data, s...)
  67. if err != nil {
  68. return 0, err
  69. }
  70. return intFromInterface(val)
  71. }
  72. // Int64 extracts an int64 from the JsonQuery
  73. func (jq *JSONQuery) Int64(s ...string) (int64, error) {
  74. val, err := rquery(jq.data, s...)
  75. if err != nil {
  76. return 0, err
  77. }
  78. return int64FromInterface(val)
  79. }
  80. // String extracts a string from the JsonQuery
  81. func (jq *JSONQuery) String(s ...string) (string, error) {
  82. val, err := rquery(jq.data, s...)
  83. if err != nil {
  84. return "", err
  85. }
  86. return stringFromInterface(val)
  87. }
  88. // Object extracts a json object from the JsonQuery
  89. func (jq *JSONQuery) Object(s ...string) (map[string]interface{}, error) {
  90. val, err := rquery(jq.data, s...)
  91. if err != nil {
  92. return map[string]interface{}{}, err
  93. }
  94. return objectFromInterface(val)
  95. }
  96. // Array extracts a []interface{} from the JsonQuery
  97. func (jq *JSONQuery) Array(s ...string) ([]interface{}, error) {
  98. val, err := rquery(jq.data, s...)
  99. if err != nil {
  100. return []interface{}{}, err
  101. }
  102. return arrayFromInterface(val)
  103. }
  104. // Interface extracts an interface{} from the JsonQuery
  105. func (jq *JSONQuery) Interface(s ...string) (interface{}, error) {
  106. val, err := rquery(jq.data, s...)
  107. if err != nil {
  108. return nil, err
  109. }
  110. return val, nil
  111. }
  112. // ArrayOfStrings extracts an array of strings from some json
  113. func (jq *JSONQuery) ArrayOfStrings(s ...string) ([]string, error) {
  114. array, err := jq.Array(s...)
  115. if err != nil {
  116. return []string{}, err
  117. }
  118. toReturn := make([]string, len(array))
  119. for index, val := range array {
  120. toReturn[index], err = stringFromInterface(val)
  121. if err != nil {
  122. return toReturn, err
  123. }
  124. }
  125. return toReturn, nil
  126. }
  127. // ArrayOfInts extracts an array of ints from some json
  128. func (jq *JSONQuery) ArrayOfInts(s ...string) ([]int, error) {
  129. array, err := jq.Array(s...)
  130. if err != nil {
  131. return []int{}, err
  132. }
  133. toReturn := make([]int, len(array))
  134. for index, val := range array {
  135. toReturn[index], err = intFromInterface(val)
  136. if err != nil {
  137. return toReturn, err
  138. }
  139. }
  140. return toReturn, nil
  141. }
  142. // ArrayOfFloats extracts an array of float64s from some json
  143. func (jq *JSONQuery) ArrayOfFloats(s ...string) ([]float64, error) {
  144. array, err := jq.Array(s...)
  145. if err != nil {
  146. return []float64{}, err
  147. }
  148. toReturn := make([]float64, len(array))
  149. for index, val := range array {
  150. toReturn[index], err = floatFromInterface(val)
  151. if err != nil {
  152. return toReturn, err
  153. }
  154. }
  155. return toReturn, nil
  156. }
  157. // ArrayOfBools extracts an array of bools from some json
  158. func (jq *JSONQuery) ArrayOfBools(s ...string) ([]bool, error) {
  159. array, err := jq.Array(s...)
  160. if err != nil {
  161. return []bool{}, err
  162. }
  163. toReturn := make([]bool, len(array))
  164. for index, val := range array {
  165. toReturn[index], err = boolFromInterface(val)
  166. if err != nil {
  167. return toReturn, err
  168. }
  169. }
  170. return toReturn, nil
  171. }
  172. // ArrayOfObjects extracts an array of map[string]interface{} (objects) from some json
  173. func (jq *JSONQuery) ArrayOfObjects(s ...string) ([]map[string]interface{}, error) {
  174. array, err := jq.Array(s...)
  175. if err != nil {
  176. return []map[string]interface{}{}, err
  177. }
  178. toReturn := make([]map[string]interface{}, len(array))
  179. for index, val := range array {
  180. toReturn[index], err = objectFromInterface(val)
  181. if err != nil {
  182. return toReturn, err
  183. }
  184. }
  185. return toReturn, nil
  186. }
  187. // ArrayOfArrays extracts an array of []interface{} (arrays) from some json
  188. func (jq *JSONQuery) ArrayOfArrays(s ...string) ([][]interface{}, error) {
  189. array, err := jq.Array(s...)
  190. if err != nil {
  191. return [][]interface{}{}, err
  192. }
  193. toReturn := make([][]interface{}, len(array))
  194. for index, val := range array {
  195. toReturn[index], err = arrayFromInterface(val)
  196. if err != nil {
  197. return toReturn, err
  198. }
  199. }
  200. return toReturn, nil
  201. }
  202. // Matrix2D is an alias for ArrayOfArrays
  203. func (jq *JSONQuery) Matrix2D(s ...string) ([][]interface{}, error) {
  204. return jq.ArrayOfArrays(s...)
  205. }
  206. // Recursively query a decoded json blob
  207. func rquery(blob interface{}, s ...string) (interface{}, error) {
  208. var (
  209. val interface{}
  210. err error
  211. )
  212. val = blob
  213. for _, q := range s {
  214. val, err = query(val, q)
  215. if err != nil {
  216. return nil, err
  217. }
  218. }
  219. switch val.(type) {
  220. case nil:
  221. return nil, fmt.Errorf("nil value")
  222. }
  223. return val, nil
  224. }
  225. // query a json blob for a single field or index. If query is a string, then
  226. // the blob is treated as a json object (map[string]interface{}). If query is
  227. // an integer, the blob is treated as a json array ([]interface{}). Any kind
  228. // of key or index error will result in a nil return value with an error set.
  229. func query(blob interface{}, query string) (interface{}, error) {
  230. index, err := strconv.Atoi(query)
  231. // if it's an integer, then we treat the current interface as an array
  232. if err == nil {
  233. switch blob.(type) {
  234. case []interface{}:
  235. default:
  236. return nil, fmt.Errorf("Array index on non-array")
  237. }
  238. if len(blob.([]interface{})) > index {
  239. return blob.([]interface{})[index], nil
  240. }
  241. return nil, fmt.Errorf("Array index %d out of bounds", index)
  242. }
  243. // blob is likely an object, but verify first
  244. switch blob.(type) {
  245. case map[string]interface{}:
  246. default:
  247. return nil, fmt.Errorf("Object lookup \"%s\" on non-object", query)
  248. }
  249. val, ok := blob.(map[string]interface{})[query]
  250. if !ok {
  251. return nil, fmt.Errorf("Object does not contain field %s", query)
  252. }
  253. return val, nil
  254. }
  255. // stringFromInterface converts an interface{} to a string and returns an error if types don't match.
  256. func stringFromInterface(val interface{}) (string, error) {
  257. switch val.(type) {
  258. case string:
  259. return val.(string), nil
  260. }
  261. return "", fmt.Errorf("Expected string value for String, got \"%v\"", val)
  262. }
  263. // boolFromInterface converts an interface{} to a bool and returns an error if types don't match.
  264. func boolFromInterface(val interface{}) (bool, error) {
  265. switch val.(type) {
  266. case bool:
  267. return val.(bool), nil
  268. }
  269. return false, fmt.Errorf("Expected boolean value for Bool, got \"%v\"", val)
  270. }
  271. // floatFromInterface converts an interface{} to a float64 and returns an error if types don't match.
  272. func floatFromInterface(val interface{}) (float64, error) {
  273. switch val.(type) {
  274. case float64:
  275. return val.(float64), nil
  276. case int:
  277. return float64(val.(int)), nil
  278. case string:
  279. fval, err := strconv.ParseFloat(val.(string), 64)
  280. if err == nil {
  281. return fval, nil
  282. }
  283. }
  284. return 0.0, fmt.Errorf("Expected numeric value for Float, got \"%v\"", val)
  285. }
  286. // intFromInterface converts an interface{} to an int and returns an error if types don't match.
  287. func intFromInterface(val interface{}) (int, error) {
  288. switch val.(type) {
  289. case float64:
  290. return int(val.(float64)), nil
  291. case string:
  292. ival, err := strconv.ParseFloat(val.(string), 64)
  293. if err == nil {
  294. return int(ival), nil
  295. }
  296. case int:
  297. return val.(int), nil
  298. }
  299. return 0, fmt.Errorf("Expected numeric value for Int, got \"%v\"", val)
  300. }
  301. func int64FromInterface(val interface{}) (int64, error) {
  302. switch val.(type) {
  303. case float64:
  304. return int64(val.(float64)), nil
  305. case string:
  306. ival, err := strconv.ParseFloat(val.(string), 64)
  307. if err == nil {
  308. return int64(ival), nil
  309. }
  310. case int:
  311. return int64(val.(int)), nil
  312. case int64:
  313. return val.(int64), nil
  314. }
  315. return 0, fmt.Errorf("Expected numeric value for Int, got \"%v\"", val)
  316. }
  317. // objectFromInterface converts an interface{} to a map[string]interface{} and returns an error if types don't match.
  318. func objectFromInterface(val interface{}) (map[string]interface{}, error) {
  319. switch val.(type) {
  320. case map[string]interface{}:
  321. return val.(map[string]interface{}), nil
  322. }
  323. return map[string]interface{}{}, fmt.Errorf("Expected json object for Object, got \"%v\"", val)
  324. }
  325. // arrayFromInterface converts an interface{} to an []interface{} and returns an error if types don't match.
  326. func arrayFromInterface(val interface{}) ([]interface{}, error) {
  327. switch val.(type) {
  328. case []interface{}:
  329. return val.([]interface{}), nil
  330. }
  331. return []interface{}{}, fmt.Errorf("Expected json array for Array, got \"%v\"", val)
  332. }