stretchr / objx

Go package for dealing with maps, slices, JSON and other data.
MIT License
687 stars 75 forks source link

help #138

Open chuckchann opened 1 year ago

chuckchann commented 1 year ago

this is my code:

func main() { data := map[string]interface{}{ "name": "Alice", "age": 30, "hobbies": []string{ "reading", "swimming", "running", }, }

obj := objx.Map(data)
obj = obj.Set("hobbies[0]", "coding")

fmt.Println("after set -> ", obj)

}

my result is: after set -> map[age:30 hobbies:sssss name:Alice]

what I expect is: after set -> map[age:30 hobbies:[coding, swimming, running] name:Alice]

it seems that there is a bug in obj.Set function when I want to modify a value in the array?

chuckchann commented 1 year ago

somebody help ?

geseq commented 1 year ago

what version are you using? I just added this test for a quick check on latest version and it passes fine


func TestSetArray(t *testing.T) {
    data := map[string]interface{}{
        "name": "Alice",
        "age":  30,
        "hobbies": []string{
            "reading",
            "swimming",
            "running",
        },
    }

    d := objx.Map(data)
    d = d.Set("hobbies[0]", "coding")
    assert.Equal(t, "coding", d.Get("hobbies[0]").String())
}
chuckchann commented 1 year ago

what version are you using? I just added this test for a quick check on latest version and it passes fine


func TestSetArray(t *testing.T) {
  data := map[string]interface{}{
      "name": "Alice",
      "age":  30,
      "hobbies": []string{
          "reading",
          "swimming",
          "running",
      },
  }

  d := objx.Map(data)
  d = d.Set("hobbies[0]", "coding")
  assert.Equal(t, "coding", d.Get("hobbies[0]").String())
}

my version is v0.5.0 in your test case, the type of struct field( "hobbies") has been change to string, you can print the object "d", here is my print result:

"map[age:30 hobbies:coding name:Alice]"

that`s why your test case passes fine