tidwall / sjson

Set JSON values very quickly in Go

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to merge objects?

nunofgs opened this issue · 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.

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.

@tidwall this feature would also help me!

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}
commented

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