Skip to content

Commit

Permalink
Merge pull request #8 from mkeesey/master
Browse files Browse the repository at this point in the history
Adding GetIndex() for traversing JSON Arrays
  • Loading branch information
mreiferson committed Aug 27, 2012
2 parents 6897943 + c3068d8 commit b387e7e
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 0 deletions.
9 changes: 9 additions & 0 deletions README.md
Expand Up @@ -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`

Expand Down
16 changes: 16 additions & 0 deletions simplejson.go
Expand Up @@ -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
//
Expand Down
12 changes: 12 additions & 0 deletions simplejson_test.go
Expand Up @@ -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,
Expand Down Expand Up @@ -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)

Expand Down

0 comments on commit b387e7e

Please sign in to comment.