Browse files

Merge pull request #8 from mkeesey/master

Adding GetIndex() for traversing JSON Arrays
  • Loading branch information...
2 parents 6897943 + c3068d8 commit b387e7e8ab0349d3264d7b208e2ed421a6f4289c @mreiferson mreiferson committed Aug 27, 2012
Showing with 37 additions and 0 deletions.
  1. +9 −0 README.md
  2. +16 −0 simplejson.go
  3. +12 −0 simplejson_test.go
View
9 README.md
@@ -56,6 +56,15 @@ func (j *Json) Get(key string) *Json
js.Get("top_level").Get("dict").Get("value").Int()
+func (j *Json) GetIndex(index int) *Json
+ GetIndex resturns a pointer to a new `Json` object for `index` in its
+ `array` representation
+
+ this is the analog to Get when accessing elements of a json array
+ instead of a json object:
+
+ js.Get("top_level").Get("array").GetIndex(1).Get("key").Int()
+
func (j *Json) Int() (int, error)
Int type asserts to `float64` then converts to `int`
View
16 simplejson.go
@@ -46,6 +46,22 @@ func (j *Json) Get(key string) *Json {
return &Json{nil}
}
+// GetIndex resturns a pointer to a new `Json` object
+// for `index` in its `array` representation
+//
+// this is the analog to Get when accessing elements of
+// a json array instead of a json object:
+// js.Get("top_level").Get("array").GetIndex(1).Get("key").Int()
+func (j *Json) GetIndex(index int) *Json {
+ a, err := j.Array()
+ if err == nil {
+ if len(a) > index {
+ return &Json{a[index]}
+ }
+ }
+ return &Json{nil}
+}
+
// CheckGet returns a pointer to a new `Json` object and
// a `bool` identifying success or failure
//
View
12 simplejson_test.go
@@ -17,6 +17,8 @@ func TestSimplejson(t *testing.T) {
js, err := NewJson([]byte(`{
"test": {
"array": [1, "2", 3],
+ "arraywithsubs": [{"subkeyone": 1},
+ {"subkeytwo": 2, "subkeythree": 3}],
"int": 10,
"float": 5.150,
"bignum": 9223372036854775807,
@@ -47,6 +49,16 @@ func TestSimplejson(t *testing.T) {
assert.Equal(t, i+1, iv)
}
+ aws := js.Get("test").Get("arraywithsubs")
+ assert.NotEqual(t, nil, aws)
+ var awsval int
+ awsval, _ = aws.GetIndex(0).Get("subkeyone").Int()
+ assert.Equal(t, 1, awsval)
+ awsval, _ = aws.GetIndex(1).Get("subkeytwo").Int()
+ assert.Equal(t, 2, awsval)
+ awsval, _ = aws.GetIndex(1).Get("subkeythree").Int()
+ assert.Equal(t, 3, awsval)
+
i, _ := js.Get("test").Get("int").Int()
assert.Equal(t, 10, i)

0 comments on commit b387e7e

Please sign in to comment.