aerospike / aerospike-client-go

Aerospike Client Go
Apache License 2.0
436 stars 199 forks source link

Getting error while marshalling the Record.Bins to json object #206

Closed dmadroja closed 7 years ago

dmadroja commented 7 years ago

I am trying to read all the records from the set and map it to struct. I am getting error while I try to marshal the rec.Record.Bins to json value

json: unsupported type: map[interface {}]interface {}

Below is my code:

stmt :=  as.NewStatement(namespace, set)
recordSet, err := db.AerospikeClient.Query(nil,stmt)

if err != nil {
    utils.LogErr("","", "Error occurred while fetching all the records from old set", err)
    return nil, err
}

for rec := range recordSet.Results() {
    marshalledJson, err := json.Marshal(rec.Record.Bins)

    if err != nil {
        utils.LogErr("","", "Error occurred while marshling all the records from old set to newsletter struct", err)
        return nil, err
    }
}

The aerospike schema is as below:

key: userId
value: {
    emailId: '',
    mailingList: [{
        name: '',
        emails: [
            {
                emailid: '',
                dateAdded: ''
            },
        ],
        updatedAt: 123,
        createdAt: 123
    }],
    unsubscriptionList: {
        name: '',
        description: '',
        emails: [
            {
                emailid: '',
                dateAdded: ''
            },
        ],
        updatedAt: 123,
        createdAt: 123
    }
}
khaf commented 7 years ago

The reason is that you have maps inside your Bins, and maps are returned as map[interface{}]interface{} by the Go client. Go's standard JSON marshaller does not accept that data type.

You have two solutions:

  1. Convert your maps to map[string]interface{}
  2. Use Query/ScanAllObjects to read the data and then marshal them.
dmadroja commented 7 years ago

I converted my map and now it is working. Thanks :) Small clarification, I am using Query in my above example so anyway I have to marshal the result Binmap which will fail. Isn't it?

khaf commented 7 years ago

QueryObject is different from Query call. It can internally marshal the Bin into Structs.

dmadroja commented 7 years ago

ohh... I checked the reflect file but overlooked it :( . Got it. Thanks