sjson icon indicating copy to clipboard operation
sjson copied to clipboard

How to merge objects?

Open nunofgs opened this issue 2 years ago • 4 comments

Thank you for sjson, its great!

Let's say I have:

object1 := `{ "one": 1 }`
object2 := `{ "two": 2, "three": 3 }`

How do I merge the two to obtain: { "one": 1, "two": 2, "three": 3 }?

I've tried:

sjson.set(object1, "", object2) // returns error
sjson.set(object1, ".", object2) // returns: { ..., "":[{"three":3}] }

Apologies if this is already possible. Wasn't obvious to me.

nunofgs avatar Jun 01 '23 14:06 nunofgs

Additionally to this, it would be great to be merge into an empty object. So give {} and merging {"foo": "bar"}, I'd expect {"foo": "bar"}. I don't believe with current syntax/functionality it's possible.

ben-wilson-peak avatar Jul 10 '23 08:07 ben-wilson-peak

@tidwall this feature would also help me!

natenho avatar Aug 06 '23 23:08 natenho

In this case you may want to use the gjson @join modifier

object1 := `{ "one": 1 }`
object2 := `{ "two": 2, "three": 3 }`
combined := gjson.Get(`[`+object1+`,`+object2+`]`, `@join`).Raw

println(combined)
// Output: {"one":1,"two":2,"three":3}

tidwall avatar Aug 09 '23 01:08 tidwall

I think it would be better to have a dedicated func for this task. for example: sjson.Join(obj1, obj2)

baxiry avatar Sep 25 '23 15:09 baxiry