Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix for bug #79 #80

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 23 additions & 3 deletions simplejson.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"encoding/json"
"errors"
"log"
"reflect"
)

// returns the current implementation version
Expand Down Expand Up @@ -60,14 +61,15 @@ func (j *Json) Set(key string, val interface{}) {
if err != nil {
return
}
m[key] = val

m[key] = handleArray(val)
}

// SetPath modifies `Json`, recursively checking/creating map keys for the supplied path,
// and then finally writing in the value
func (j *Json) SetPath(branch []string, val interface{}) {
if len(branch) == 0 {
j.data = val
j.data = handleArray(val)
return
}

Expand Down Expand Up @@ -99,7 +101,7 @@ func (j *Json) SetPath(branch []string, val interface{}) {
}

// add remaining k/v
curr[branch[len(branch)-1]] = val
curr[branch[len(branch)-1]] = handleArray(val)
}

// Del modifies `Json` map by deleting `key` if it is present.
Expand Down Expand Up @@ -444,3 +446,21 @@ func (j *Json) MustUint64(args ...uint64) uint64 {

return def
}

func handleArray(val interface{}) interface{} {
if val != nil {
// If val is an array convert to []interface{}
typ := reflect.TypeOf(val)
kind := typ.Kind()
if kind == reflect.Array || kind == reflect.Slice {

v := reflect.ValueOf(val)
arr := make([]interface{}, v.Len())
for i := 0; i < v.Len(); i++ {
arr[i] = v.Index(i).Interface()
}
val = arr
}
}
return val
}
18 changes: 18 additions & 0 deletions simplejson_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,24 @@ func TestSimplejson(t *testing.T) {

js.GetPath("test", "sub_obj").Set("a", 3)
assert.Equal(t, 3, js.GetPath("test", "sub_obj", "a").MustInt())

a := [3]string{"one", "two", "three"}
js = New()
js.Set("array", a)
a2, err := js.Get("array").Array()
assert.Equal(t, nil, err)
assert.NotEqual(t, nil, a2)
assert.Equal(t, a2[0], "one")
assert.Equal(t, a2[1], "two")
assert.Equal(t, a2[2], "three")

a3, err := js.Get("array").StringArray()
assert.Equal(t, nil, err)
assert.NotEqual(t, nil, a3)
assert.Equal(t, a3[0], "one")
assert.Equal(t, a3[1], "two")
assert.Equal(t, a3[2], "three")

}

func TestStdlibInterfaces(t *testing.T) {
Expand Down