sjson icon indicating copy to clipboard operation
sjson copied to clipboard

Need to set array of values to array of objects.

Open Rushi-Kumar opened this issue 2 years ago • 1 comments

need to set multiple values for an array of objects

package main

import (
	"fmt"

	"github.com/tidwall/sjson"
)

const jsondata = `{"data":[]}`

func main() {
	data := make([]string, 0)
	data = append(data, "sos", "msa", "kkh")
	value, err := sjson.Set(jsondata, "data.#.name", data)
	if err != nil {
		fmt.Println(err)
	}
	println(value)

}

expected result

{data:[{name:"sos"},{name:"msa"},{name:"kkh"}]

output result

{"data":[]}

from my understanding of the source code, I have observed that the value is converted to a string and replaced at the exact path. is there any possible way to implement this?. However, we will be able to map the array by providing an index number instead of #

value, err := sjson.Set(jsondata, "data.0.name", data[0])
value, err = sjson.Set(value, "data.1.name", data[1])

Rushi-Kumar avatar Apr 12 '22 07:04 Rushi-Kumar

jsonData := `{"data":[]}`

data := make([]string, 0)
data = append(data, "sos", "msa", "kkh")

for _, v := range data {
	jsonData, _ = sjson.Set(jsonData, "data.-1.name", v)
}

println(jsonData)

BeforyDeath avatar Jun 01 '22 11:06 BeforyDeath