Jeffail/gabs

restructure a json object

aqsyonas opened this issue · 2 comments

Greetings,
I have a JSON object like below.

[
  {
    "create_date": "2019-08-28T07:01:20.000332-04:00",
    "data_header": {
      "callid": "first@127.0.0.1"
    },
    "id": 761,
    "protocol_header": {
      "captureId": "2001"
    },
    "sid": "b1ki@127.0.0.1"
  },
  {
    "create_date": "2019-08-28T07:01:30.000581-04:00",
    "data_header": {
      "callid": "second@127.0.0.1"
    },
    "id": 762,
    "protocol_header": {
      "captureId": "2002"
    },
    "sid": "b1ki@127.0.0.1"
  }
]

I would like to restructure it like below.

[
  {
    "callid": "first@127.0.0.1",
    "captureId": "2001",
    "create_date": "2019-08-28T07:01:20.000332-04:00",
    "id": 761,
    "sid": "b1ki@127.0.0.1"
  },
  {
    "callid": "second@127.0.0.1",
    "captureId": "2002",
    "create_date": "2019-08-28T07:01:30.000581-04:00",
    "id": 762,
    "sid": "b1ki@127.0.0.1"
  }
]

I have tried so far this https://play.golang.org/p/g_9W08zigif but my method is adding an empty object into array.

Any suggestion how can I handle this better?

Best Regards,

Hey @aqsyonas, if you start off by wrapping an array then it'll work as expected: https://play.golang.org/p/NE5Y_7R_EMa

Otherwise if you start off with gabs.New you initialise an empty object, and the first call to append will place the original empty object as the first element.

@Jeffail superb, first method looks clear and exactly what I wanted.

Thanks for being really helpful here.