Tonyukuk
Tonyukuk

Reputation: 6215

How to get an error while marshaling not json

I have a map whose key his string and value is an interface. I an putting some keys and values into that map I want to marshal it but I want to get a "nonvalid" or I want my marshal comes with an error? In order to succeed it, what kind of variables do I need to put into that map?

myBlobMap := make(map[string]interface{})
blobmap["firstKey"] = "firstValue"
blobmap["secondKey"] = "secondValue"
jsonByte, err := json.Marshal(myBlobMap)

Upvotes: 0

Views: 400

Answers (1)

TehSphinX
TehSphinX

Reputation: 7440

From the Go documentation on json:

Channel, complex, and function values cannot be encoded in JSON. Attempting to encode such a value causes Marshal to return an UnsupportedTypeError.

JSON cannot represent cyclic data structures and Marshal does not handle them. Passing cyclic structures to Marshal will result in an error.

Here an example with a function that will return an error:

package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    myBlobMap := make(map[string]interface{})
    myBlobMap["firstKey"] = func() {}
    myBlobMap["secondKey"] = "secondValue"
    jsonByte, err := json.Marshal(myBlobMap)
    fmt.Print(jsonByte, err)
}

Playground

Upvotes: 2

Related Questions