From c3068d8d6c27d3ee9f045f25157b4299fcb540c2 Mon Sep 17 00:00:00 2001 From: Mike Keesey Date: Sun, 26 Aug 2012 20:20:12 -0600 Subject: [PATCH] Add GetIndex(), add test for it. Similarly to Get(), GetIndex() allows you to chain together calls that involve JSON nested within JSON arrays. --- README.md | 9 +++++++++ simplejson.go | 16 ++++++++++++++++ simplejson_test.go | 12 ++++++++++++ 3 files changed, 37 insertions(+) diff --git a/README.md b/README.md index 681d6c2..30e46dc 100644 --- a/README.md +++ b/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` diff --git a/simplejson.go b/simplejson.go index 9701907..b0a5535 100644 --- a/simplejson.go +++ b/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 // diff --git a/simplejson_test.go b/simplejson_test.go index 6ad4b60..91d989d 100644 --- a/simplejson_test.go +++ b/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)