How to parse message body "topology" in Maelstrom exercise?

I’m trying to parse the “topology” field in this problem: Challenge #3b: Multi-Node Broadcast · Fly Docs

It looks to me like the type should be a map[string]([]string).

My code is:

// this is initialized in a different place
var nodeId string

// code that's failing
topology := body["topology"].(map[string]any)
neighborNodeIds = topology[nodeId].([]string)

This is running into the error:

2023/03/05 17:23:30 Received {c9 n4 {"type":"topology","topology":{"n0":["n3","n1"],"n1":["n4","n2","n0"],"n2":["n1"],"n3":["n0","n4"],"n4":["n1","n3"]},"msg_id":1}}
panic: interface conversion: interface {} is []interface {}, not []string

What should I do to parse it into a map[string]([]string)?

The trick is to pass in the structure you want to parse into the json.Unmarshal() function and then Go will handle it. If you decode JSON into a generic interface{} or any type then it’ll use the most generic types when decoding (e.g. []interface{}).

Define your type:

type TopologyMessageBody struct {
	Type     string              `json:"type"`
	Topology map[string][]string `json:"topology"`

Then pass a reference to an instance into json.Unmarshal():

var body TopologyMessageBody
if err := json.Unmarshal(bodyData, &body); err != nil {
	return err
1 Like

This worked, thank you!