json.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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. // String extracts a string from the JsonQuery
  73. func (jq *JSONQuery) String(s ...string) (string, error) {
  74. val, err := rquery(jq.data, s...)
  75. if err != nil {
  76. return "", err
  77. }
  78. return stringFromInterface(val)
  79. }
  80. // Object extracts a json object from the JsonQuery
  81. func (jq *JSONQuery) Object(s ...string) (map[string]interface{}, error) {
  82. val, err := rquery(jq.data, s...)
  83. if err != nil {
  84. return map[string]interface{}{}, err
  85. }
  86. return objectFromInterface(val)
  87. }
  88. // Array extracts a []interface{} from the JsonQuery
  89. func (jq *JSONQuery) Array(s ...string) ([]interface{}, error) {
  90. val, err := rquery(jq.data, s...)
  91. if err != nil {
  92. return []interface{}{}, err
  93. }
  94. return arrayFromInterface(val)
  95. }
  96. // Interface extracts an interface{} from the JsonQuery
  97. func (jq *JSONQuery) Interface(s ...string) (interface{}, error) {
  98. val, err := rquery(jq.data, s...)
  99. if err != nil {
  100. return nil, err
  101. }
  102. return val, nil
  103. }
  104. // ArrayOfStrings extracts an array of strings from some json
  105. func (jq *JSONQuery) ArrayOfStrings(s ...string) ([]string, error) {
  106. array, err := jq.Array(s...)
  107. if err != nil {
  108. return []string{}, err
  109. }
  110. toReturn := make([]string, len(array))
  111. for index, val := range array {
  112. toReturn[index], err = stringFromInterface(val)
  113. if err != nil {
  114. return toReturn, err
  115. }
  116. }
  117. return toReturn, nil
  118. }
  119. // ArrayOfInts extracts an array of ints from some json
  120. func (jq *JSONQuery) ArrayOfInts(s ...string) ([]int, error) {
  121. array, err := jq.Array(s...)
  122. if err != nil {
  123. return []int{}, err
  124. }
  125. toReturn := make([]int, len(array))
  126. for index, val := range array {
  127. toReturn[index], err = intFromInterface(val)
  128. if err != nil {
  129. return toReturn, err
  130. }
  131. }
  132. return toReturn, nil
  133. }
  134. // ArrayOfFloats extracts an array of float64s from some json
  135. func (jq *JSONQuery) ArrayOfFloats(s ...string) ([]float64, error) {
  136. array, err := jq.Array(s...)
  137. if err != nil {
  138. return []float64{}, err
  139. }
  140. toReturn := make([]float64, len(array))
  141. for index, val := range array {
  142. toReturn[index], err = floatFromInterface(val)
  143. if err != nil {
  144. return toReturn, err
  145. }
  146. }
  147. return toReturn, nil
  148. }
  149. // ArrayOfBools extracts an array of bools from some json
  150. func (jq *JSONQuery) ArrayOfBools(s ...string) ([]bool, error) {
  151. array, err := jq.Array(s...)
  152. if err != nil {
  153. return []bool{}, err
  154. }
  155. toReturn := make([]bool, len(array))
  156. for index, val := range array {
  157. toReturn[index], err = boolFromInterface(val)
  158. if err != nil {
  159. return toReturn, err
  160. }
  161. }
  162. return toReturn, nil
  163. }
  164. // ArrayOfObjects extracts an array of map[string]interface{} (objects) from some json
  165. func (jq *JSONQuery) ArrayOfObjects(s ...string) ([]map[string]interface{}, error) {
  166. array, err := jq.Array(s...)
  167. if err != nil {
  168. return []map[string]interface{}{}, err
  169. }
  170. toReturn := make([]map[string]interface{}, len(array))
  171. for index, val := range array {
  172. toReturn[index], err = objectFromInterface(val)
  173. if err != nil {
  174. return toReturn, err
  175. }
  176. }
  177. return toReturn, nil
  178. }
  179. // ArrayOfArrays extracts an array of []interface{} (arrays) from some json
  180. func (jq *JSONQuery) ArrayOfArrays(s ...string) ([][]interface{}, error) {
  181. array, err := jq.Array(s...)
  182. if err != nil {
  183. return [][]interface{}{}, err
  184. }
  185. toReturn := make([][]interface{}, len(array))
  186. for index, val := range array {
  187. toReturn[index], err = arrayFromInterface(val)
  188. if err != nil {
  189. return toReturn, err
  190. }
  191. }
  192. return toReturn, nil
  193. }
  194. // Matrix2D is an alias for ArrayOfArrays
  195. func (jq *JSONQuery) Matrix2D(s ...string) ([][]interface{}, error) {
  196. return jq.ArrayOfArrays(s...)
  197. }
  198. // Recursively query a decoded json blob
  199. func rquery(blob interface{}, s ...string) (interface{}, error) {
  200. var (
  201. val interface{}
  202. err error
  203. )
  204. val = blob
  205. for _, q := range s {
  206. val, err = query(val, q)
  207. if err != nil {
  208. return nil, err
  209. }
  210. }
  211. switch val.(type) {
  212. case nil:
  213. return nil, fmt.Errorf("nil value")
  214. }
  215. return val, nil
  216. }
  217. // query a json blob for a single field or index. If query is a string, then
  218. // the blob is treated as a json object (map[string]interface{}). If query is
  219. // an integer, the blob is treated as a json array ([]interface{}). Any kind
  220. // of key or index error will result in a nil return value with an error set.
  221. func query(blob interface{}, query string) (interface{}, error) {
  222. index, err := strconv.Atoi(query)
  223. // if it's an integer, then we treat the current interface as an array
  224. if err == nil {
  225. switch blob.(type) {
  226. case []interface{}:
  227. default:
  228. return nil, fmt.Errorf("Array index on non-array")
  229. }
  230. if len(blob.([]interface{})) > index {
  231. return blob.([]interface{})[index], nil
  232. }
  233. return nil, fmt.Errorf("Array index %d out of bounds", index)
  234. }
  235. // blob is likely an object, but verify first
  236. switch blob.(type) {
  237. case map[string]interface{}:
  238. default:
  239. return nil, fmt.Errorf("Object lookup \"%s\" on non-object", query)
  240. }
  241. val, ok := blob.(map[string]interface{})[query]
  242. if !ok {
  243. return nil, fmt.Errorf("Object does not contain field %s", query)
  244. }
  245. return val, nil
  246. }
  247. // stringFromInterface converts an interface{} to a string and returns an error if types don't match.
  248. func stringFromInterface(val interface{}) (string, error) {
  249. switch val.(type) {
  250. case string:
  251. return val.(string), nil
  252. }
  253. return "", fmt.Errorf("Expected string value for String, got \"%v\"", val)
  254. }
  255. // boolFromInterface converts an interface{} to a bool and returns an error if types don't match.
  256. func boolFromInterface(val interface{}) (bool, error) {
  257. switch val.(type) {
  258. case bool:
  259. return val.(bool), nil
  260. }
  261. return false, fmt.Errorf("Expected boolean value for Bool, got \"%v\"", val)
  262. }
  263. // floatFromInterface converts an interface{} to a float64 and returns an error if types don't match.
  264. func floatFromInterface(val interface{}) (float64, error) {
  265. switch val.(type) {
  266. case float64:
  267. return val.(float64), nil
  268. case int:
  269. return float64(val.(int)), nil
  270. case string:
  271. fval, err := strconv.ParseFloat(val.(string), 64)
  272. if err == nil {
  273. return fval, nil
  274. }
  275. }
  276. return 0.0, fmt.Errorf("Expected numeric value for Float, got \"%v\"", val)
  277. }
  278. // intFromInterface converts an interface{} to an int and returns an error if types don't match.
  279. func intFromInterface(val interface{}) (int, error) {
  280. switch val.(type) {
  281. case float64:
  282. return int(val.(float64)), nil
  283. case string:
  284. ival, err := strconv.ParseFloat(val.(string), 64)
  285. if err == nil {
  286. return int(ival), nil
  287. }
  288. case int:
  289. return val.(int), nil
  290. }
  291. return 0, fmt.Errorf("Expected numeric value for Int, got \"%v\"", val)
  292. }
  293. // objectFromInterface converts an interface{} to a map[string]interface{} and returns an error if types don't match.
  294. func objectFromInterface(val interface{}) (map[string]interface{}, error) {
  295. switch val.(type) {
  296. case map[string]interface{}:
  297. return val.(map[string]interface{}), nil
  298. }
  299. return map[string]interface{}{}, fmt.Errorf("Expected json object for Object, got \"%v\"", val)
  300. }
  301. // arrayFromInterface converts an interface{} to an []interface{} and returns an error if types don't match.
  302. func arrayFromInterface(val interface{}) ([]interface{}, error) {
  303. switch val.(type) {
  304. case []interface{}:
  305. return val.([]interface{}), nil
  306. }
  307. return []interface{}{}, fmt.Errorf("Expected json array for Array, got \"%v\"", val)
  308. }