How to copy or reference an array of source Container in a new Container?
Closed this issue · 1 comments
MaciekLeks commented
I'm trying to create a new Container based on the source one. The problem I found out is with copying or referencing a part of original Container in a new one. As the Result2 shows doing it my way does not work.
package main
import (
"fmt"
"github.com/Jeffail/gabs"
)
func main() {
const json = `
{
"name": {"first": "Tom", "last": "Anderson"},
"age":37,
"children": ["Sara","Alex","Jack"],
"fav.movie": "Deer Hunter",
"friends": [
{"first": "Dale", "last": "Murphy", "age": 44, "nets": ["ig", "fb", "tw"]},
{"first": "Roger", "last": "Craig", "age": 68, "nets": ["fb", "tw"]},
{"first": "Jane", "last": "Murphy", "age": 47, "nets": ["ig", "tw"]}
]
}`
jsonSrc, _ := gabs.ParseJSON([]byte(json))
jsonNew := gabs.New()
jsonNew.Set("Brandon Jason", "name")
//this not works also: jsonObj.Set(src.S("friends"), "friends")
jsonNew.Array("friends")
for _, friend := range jsonSrc.S("friends").Children() {
jsonNew.ArrayAppend(friend, "friends")
}
fmt.Println("Result1:", jsonNew.String())
// Result1: {"friends":[{"age":44,"first":"Dale","last":"Murphy","nets":["ig","fb","tw"]},{"age":68,"first":"Roger","last":"Craig","nets":["fb","tw"]},{"age":47,"first":"Jane","last":"Murphy","nets":["ig","tw"]}],"name":"Brandon Jason"}
fmt.Println("Result2:", jsonNew.Path("friends.0.last").String())
// Result2: null
}
MaciekLeks commented
OK. I found out the answer in the issue 61.
I should append the data as follows:
jsonNew.ArrayAppend(friend.Data(), "friends")
Then. It works.