Jeffail/gabs

Container.Set does not take effect on parent node if param "hierarchy" is empty

Closed this issue · 5 comments

func test() {
	bs := []byte(`{"name":{"first":"jim","last":"raynor"}}`)

	data, _ := gabs.ParseJSON(bs)
	_, _ = data.Set("bond", "name", "last")
	fmt.Println(data.String())
	// output : {"name":{"first":"jim","last":"bond"}}

	data1, _ := gabs.ParseJSON(bs)
	data11 := data1.S("name")
	_, _ = data11.Set("bond", "last")
	fmt.Println(data1.String())
	// output : {"name":{"first":"jim","last":"bond"}}

	data2, _ := gabs.ParseJSON(bs)
	data22 := data2.S("name", "last")
	_, _ = data22.Set("bond")
	fmt.Println(data2.String())
	// output : {"name":{"first":"jim","last":"raynor"}}
}
  • env
    go 1.17

  • What happened ?
    data2 has not been changed.

  • What is expected ?
    data2 has been changed as same as data and data1.

func test2() {
	bs := []byte(`["james","raynor"]`)
	data, _ := gabs.ParseJSON(bs)
	ds := data.Children()
	for i := range ds {
		nv, _ := ds[i].Set("bond")
		ds[i] = nv
	}
	fmt.Println(data.String())
	// output : ["james","raynor"]
}

It is troublesome to iterate arrays.

Hey, thanks for trying Gabs! I think this relates to #91.

For your first example, data22.Set("bond") doesn't change data2, so you'll need to do data2.Set(data22, "name", "last") before printing data2.

For your second example, try this:

func test2() {
	bs := []byte(`["james","raynor"]`)
	data, _ := gabs.ParseJSON(bs)
	ds := data.Children()
	for i := range ds {
		nv, _ := ds[i].Set("bond")
		_, _ = data.SetIndex(nv.Data(), i)
	}
	fmt.Println(data.String())
	// output : ["bond","bond"]
}

Hope this helps.

Thank you a lot for response! Your advice to the second example is helpful.

For the first example, what confused to me is data11.Set("bond", "last") will change value of data1, but data22.Set("bond") will not change value of data2.

You're welcome! Yeah, I agree, there are some inconsistencies in the API as mentioned in the issue I linked to. Not sure if there are any plans to address them for the time being.

I got it. Thanks!