msgpack icon indicating copy to clipboard operation
msgpack copied to clipboard

Can't unmarshal `map[string]any`

Open jney opened this issue 3 months ago • 4 comments

code:

package main

import (
	"encoding/json"

	"github.com/rs/zerolog/log"
	"github.com/shamaton/msgpack/v2"
)

type foo struct {
	Parameters map[string]any `json:"parameters,omitempty" msgpack:"parameters,omitempty"`
}

func main() {
	b := []byte(`{"parameters":{"a":{"b":"foo","c":"bar","d":5.37}}}`)
	e := &foo{}
	err := json.Unmarshal(b, e)
	if err != nil {
		log.Fatal().Err(err).Msg("json unmarshal")
	}
	b, err = msgpack.Marshal(e)
	log.Debug().Err(err).Bytes("bytes", b).Msg("marshal")

	e = &foo{}
	err = msgpack.Unmarshal(b, e)
	log.Debug().Err(err).Interface("event", e).Msg("unmarshal")
}

output:

{"level":"debug","bytes":"\ufffd\ufffdparameters\ufffd\ufffda\ufffd\ufffdb\ufffdfoo\ufffdc\ufffdbar\ufffdd\ufffd@\u0015z\ufffdG\ufffd\u0014{","time":"2025-09-09T10:00:52+02:00","message":"marshal"}
{"level":"debug","event":"marshaling error: json: unsupported type: map[interface {}]interface {}","time":"2025-09-09T10:00:52+02:00","message":"unmarshal"}

Is there a way to unmarshal map[string]any?

jney avatar Sep 09 '25 08:09 jney

It seems like zerolog has a problem. Default Loggers like log or slog have no problem.

https://go.dev/play/p/yLNwYaES09y

shamaton avatar Sep 10 '25 00:09 shamaton

Thanks for your reply! Yes it looks like it is actually a json issue. https://go.dev/play/p/XmuEtWZGdLO The library is behaving differently from vmihailenco's one. Do you think I can handle it using a customized Decode or something like that?

jney avatar Sep 11 '25 08:09 jney

I figured out the cause of different behaviour and specific code lines but it seems to need to change larger than I expected. I'm sorry but I can't handle it immediately.

Do you think I can handle it using a customized Decode or something like that?

You might be able to handle it but I would say the type(map[string]any) is difficult to handle.

shamaton avatar Sep 26 '25 12:09 shamaton

This issue is stale because it has been open for 30 days with no activity.

github-actions[bot] avatar Oct 27 '25 11:10 github-actions[bot]