Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to merge objects? #69

Open
nunofgs opened this issue Jun 1, 2023 · 4 comments
Open

How to merge objects? #69

nunofgs opened this issue Jun 1, 2023 · 4 comments

Comments

@nunofgs
Copy link

nunofgs commented Jun 1, 2023

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
Copy link

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
Copy link

natenho commented Aug 6, 2023

@tidwall this feature would also help me!

@tidwall
Copy link
Owner

tidwall commented Aug 9, 2023

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
Copy link

baxiry commented Sep 25, 2023

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants