OLD | NEW |
(Empty) | |
| 1 // Copyright 2015 The Chromium Authors. All rights reserved. |
| 2 // Use of this source code is governed by a BSD-style license that can be |
| 3 // found in the LICENSE file. |
| 4 |
| 5 package jsutil |
| 6 |
| 7 import ( |
| 8 "fmt" |
| 9 ) |
| 10 |
| 11 // Get is like GetError, except that if GetError would return an error, this |
| 12 // function panics instead. |
| 13 func Get(data interface{}, pathElems ...interface{}) interface{} { |
| 14 r, err := GetError(data, pathElems...) |
| 15 if err != nil { |
| 16 panic(err) |
| 17 } |
| 18 return r |
| 19 } |
| 20 |
| 21 // GetError retrieves a value from a 'jsonish' data object, given a path to |
| 22 // follow. |
| 23 // |
| 24 // data is assumed to be either a map[string]interface{}, or a []interface{}. |
| 25 // |
| 26 // pathElems should either be strings or int's. Any other type will cause a |
| 27 // panic. So don't do it. |
| 28 // |
| 29 // A pathElem of a string implies that GetError should expect a map at that |
| 30 // location in the jsonish data. An int implies that it should expect a list. |
| 31 // If this expectation is false, an error is returned. |
| 32 // |
| 33 // If you attempt to index into a list such that the index is out of bounds, |
| 34 // you'll get a panic just like if you passed an index to a slice that was out |
| 35 // of bounds. |
| 36 // |
| 37 // Accessing a map key which doesn't exist will return nil. |
| 38 // |
| 39 // Example: |
| 40 // data = { |
| 41 // "some": [ |
| 42 // {"nested": {"value": 10}} |
| 43 // ] |
| 44 // } |
| 45 // |
| 46 // GetError(data, "some") #=> [{"nested":...}] |
| 47 // GetError(data, "some", 0) #=> {"nested":...} |
| 48 // GetError(data, "some", 0, "nested") #=> {"value": 10} |
| 49 // GetError(data, "some", 0, "nested", "value") #=> 10 |
| 50 // GetError(data, "wat") #=> nil |
| 51 // GetError(data, "wat", "something") #=> panic(nil deref) |
| 52 // GetError(data, "some", 1) #=> panic(out of bounds) |
| 53 func GetError(data interface{}, pathElems ...interface{}) (interface{}, error) { |
| 54 for len(pathElems) > 0 { |
| 55 idx := pathElems[0] |
| 56 pathElems = pathElems[1:] |
| 57 switch i := idx.(type) { |
| 58 case int: |
| 59 d, ok := data.([]interface{}) |
| 60 if !ok { |
| 61 return nil, fmt.Errorf("jsutil.GetError: expecte
d []interface{}, but got %T", data) |
| 62 } |
| 63 data = d[i] |
| 64 case string: |
| 65 d, ok := data.(map[string]interface{}) |
| 66 if !ok { |
| 67 return nil, fmt.Errorf("jsutil.GetError: expecte
d map[string]interface{}, but got %T", data) |
| 68 } |
| 69 data = d[i] |
| 70 default: |
| 71 return nil, fmt.Errorf("jsutil.GetError: expected string
or int in pathElems, got %T instead", idx) |
| 72 } |
| 73 } |
| 74 return data, nil |
| 75 } |
OLD | NEW |