JSON Marshal Rejects Channels And Funcs
json.Marshal fails on chan and func fields: errors.As recovers *json.UnsupportedTypeError naming the exact Go type, so the wire keeps only encodable data.
Code
package main
import (
"encoding/json"
"errors"
"fmt"
)
type Job struct {
Name string
Done chan struct{} // channel 无法编码成 JSON
Format func() // 函数同样不行
}
func main() {
job := Job{Name: "index", Done: make(chan struct{})}
_, err := json.Marshal(job)
fmt.Println("marshal failed:", err != nil)
// 错误是 *json.UnsupportedTypeError,errors.As 取出出错的具体 Go 类型
var ute *json.UnsupportedTypeError
if errors.As(err, &ute) {
fmt.Println("type:", ute.Type)
}
// 修复:通道和函数留在内部结构里,序列化边界只暴露可编码数据
wire, _ := json.Marshal(struct{ Name string }{Name: job.Name})
fmt.Println("wire:", string(wire))
}Inside the snippet
JSON Marshal Rejects Channels And Funcs is built around the function main.
Points of care
- No package manager involved — every call resolves to a built-in API.
Putting it to use
Signature: func main()
The file announces its steps in the output: marshal failed:, type:, wire:.
Lines worth quoting
job := Job{Name: "index", Done: make(chan struct{})}
if errors.As(err, &ute) {
fmt.Println("type:", ute.Type)
}
Interactive Tools for This Topic
CSV to JSON ConverterConvert comma-separated values into a JSON array of objects using the first row as field names, with support for quoted and escaped fields.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.
FAQ
- What does JSON Marshal Rejects Channels And Funcs print when run?
- Invoke the file as-is — the `marshal failed:`, `type:`, `wire:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.