Skip to content
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
20 changes: 19 additions & 1 deletion simplejson.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,19 +53,37 @@ func (j *Json) MarshalJSON() ([]byte, error) {
return json.Marshal(&j.data)
}

// unwrapJSON stores the underlying payload when val is a Json wrapper.
// Get() wraps map values in a new Json; leaving a *Json in the map would
// make nested Get/Map fail because they type-assert to map[string]interface{}.
func unwrapJSON(val interface{}) interface{} {
switch v := val.(type) {
case *Json:
if v == nil {
return nil
}
return v.data
case Json:
return v.data
default:
return val
}
}

// Set modifies `Json` map by `key` and `value`
// Useful for changing single key/value in a `Json` object easily.
func (j *Json) Set(key string, val interface{}) {
m, err := j.Map()
if err != nil {
return
}
m[key] = val
m[key] = unwrapJSON(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{}) {
val = unwrapJSON(val)
if len(branch) == 0 {
j.data = val
return
Expand Down
42 changes: 42 additions & 0 deletions simplejson_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,48 @@ func TestSet(t *testing.T) {
}
}

func TestSetJsonValue(t *testing.T) {
xx, err := NewJson([]byte(`{"name": "Alice"}`))
if err != nil {
t.Fatalf("err %#v", err)
}

yy := New()
yy.Set("Contact", xx)
s, err := yy.Get("Contact").Get("name").String()
if err != nil {
t.Fatalf("err %#v", err)
}
if s != "Alice" {
t.Errorf("got %#v", s)
}

yy2 := New()
yy2.Set("Contact", xx.Interface())
s, err = yy2.Get("Contact").Get("name").String()
if err != nil {
t.Fatalf("err %#v", err)
}
if s != "Alice" {
t.Errorf("got %#v", s)
}

yy.SetPath([]string{"nested", "contact"}, xx)
s, err = yy.GetPath("nested", "contact", "name").String()
if err != nil {
t.Fatalf("err %#v", err)
}
if s != "Alice" {
t.Errorf("got %#v", s)
}

var n *Json
yy.Set("empty", n)
if yy.Get("empty").Interface() != nil {
t.Errorf("nil *Json should store nil, got %#v", yy.Get("empty").Interface())
}
}

func TestReplace(t *testing.T) {
js, err := NewJson([]byte(`{}`))
if err != nil {
Expand Down