mgo error when unmarshal map[string]interface{}


I want to store an arbitrary json object in a struct:

type C struct {
  Name string `json:"name" bson:"name"`
  Config map[string]interface{} `json:"config" bson:"config"`

This works fine when I store any deeply nested json object, but when I go retrieve it and mgo tries to Unmarshal it, I get:

Unmarshal can’t deal with struct values. Use a pointer.

I’m not sure what’s supposed to be a pointer. I get the same errors if I change it to:

Config *map[string]interface{}

The error occurs here:

I don’t know what it’s reflecting on though.


So when you are unmarshaling the input argument takes a pointer to the struct, and you need to define a type in order to use a pointer to a struct.

type myMap map[string]interface{}

Then you can make a pointer to that type notice the ampersand to indicate pointer to your struct for type myMap, with json you could do something like so:

json := []Byte{`{"name": "value"}`}
c := &myMap{"value": "name"}
json.Unmarshal(c, json)

So you need *myMap to the struct not a pointer to the type. In order to explain the specific solution to this problem you need to add the context of how mongodb is unmarshaling your json.

Answered By – Adrian Forsius

Answer Checked By – Willingham (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.