tidwall / sjson

Set JSON values very quickly in Go
MIT License
2.4k stars 165 forks source link

How to merge objects? #69

Open nunofgs opened 1 year ago

nunofgs commented 1 year ago

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.

ben-wilson-peak commented 1 year ago

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.

natenho commented 1 year ago

@tidwall this feature would also help me!

tidwall commented 1 year ago

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}
baxiry commented 11 months ago

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