Jeffail/gabs

how to merge two arrays

Closed this issue · 8 comments

Greetings,
i have two json objects like below.
First One.

[
  {
    "data_header": {
      "callid": "wwt3l4@127.0.0.1_b2b-1"
    },
    "id": 676,
    "protocol_header": {
      "captureId": "2001"
    }
  }
]

Second One.

[
  {
    "id": 54,
    "protocol_header": {
      "captureId": "2002"
    },
    "data_header": {
      "callid": "aa@127.0.0.1",
      "node": "2001"
    }
  }
]

I would like to merge them so they like below.

[
  {
    "id": 54,
    "protocol_header": {
      "captureId": "2002"
    },
    "data_header": {
      "callid": "aa@127.0.0.1",
      "node": "2001"
    }
  },
  {
    "data_header": {
      "callid": "wwt3l4@127.0.0.1_b2b-1"
    },
    "id": 676,
    "protocol_header": {
      "captureId": "2001"
    }
  }
]

Any hint how can I achieve the above result?
Best Regards,

Hey @aqsyonas, there's a merge function (https://godoc.org/github.com/Jeffail/gabs#Container.Merge) that should handle that for you.

@Jeffail Thanks for the response. Looks like Merge method does not work with arrays.
I have created a simple program to verify that.

https://play.golang.org/p/3EGmUQFqGDc

Thanks again for your help.

Ah okay, yes this won't work if the arrays are at the root of the JSON document, you'd need to have them within an object: https://play.golang.org/p/3spdW3TQ7a9. For now you could work around this by placing the arrays within the field of an object, merge the objects, then extract the array.

@Jeffail Thanks for the awesome library and support. Just last question, How can I make above array into object by adding foo as key. I have tried this https://play.golang.org/p/M_q1FrhKJtj but is not working as expected.

Hey @aqsyonas, in your case it would look like this: https://play.golang.org/p/YfKmTIhecTu

@Jeffail Sorry, your json object had already had "foo" at the root, and you were adding it again. Unfortunately, this is not working for me here https://play.golang.org/p/rGZoHuVyBDC

Thanks again for your help. :)

@Jeffail perfect that one worked for me. I wish I could give more stars to you. :)

Many thanks.