我正在使用一个 Go 应用程序,需要将原始 JSON 数据传递给结构字段,但在编组结构时遇到了额外转义的问题,尤其是当原始 JSON 包含空格和制表符时。具体来说,我使用以下结构:
type BrandTemplate struct {
Type string `json:"type"` // Template type (e.g., email_forgot_password)
Locale string `json:"locale"` // Locale (e.g., "es" for Spanish, "en" for English)
Template string `json:"template"` // Template content (Email/SMS content)
}
type BrandTemplate1 struct {
Type string `json:"type"`
Locale string `json:"locale"`
Template json.RawMessage `json:"template"` // Use RawMessage to avoid extra escaping
}
该BrandTemplate
结构期望模板字段是一个字符串,但我需要传递的原始 JSON 包含空格、制表符和需要转义的特殊字符,而我不想手动转义。
另一方面,BrandTemplate1
结构体使用json.RawMessage
,它工作得很好,因为它保留了原始 JSON 格式。但我想使用BrandTemplate
结构体,我想知道是否有办法避免手动转义 JSON 字符串并以干净的方式传递原始 JSON,同时保留空格、制表符和其他格式。
下面是我正在尝试做的一个例子:
// Define the template as raw JSON
template := `{
"subject": "Email MFA App Verification Code",
"html": "<html><head></head><body><p>Here is the code: {{otp_code}}</p></body></html>",
"plain": "Here is the code: {{otp_code}}"
}`
// Create a new BrandTemplate object
brandTemplate := models.BrandTemplate{
Type: "email_code_app_verification", // Example template type
Locale: "en", // Locale for the template (English)
Template: template, // Pass the raw JSON string
}
这是我打印时得到的输出brandTemplate
:
BrandTemplate JSON:
{
"type": "email_code_app_verification",
"locale": "en",
"template": "{\n\t\t\"subject\": \"Email MFA App Verification Code\",\n\t\t\"html\": \"\\u003chtml\\u003e\\u003chead\\u003e\\u003c/head\\u003e\\u003cbody\\u003e\\u003cp\\u003eHere is the code: {{otp_code}}\\u003c/p\\u003e\\u003c/body\\u003e\\u003c/html\\u003e\",\n\t\t\"plain\": \"Here is the code: {{otp_code}}\"\n\t}"
}
这是预期的输出:
BrandTemplate JSON:
{
"type": "email_code_app_verification",
"locale": "en",
"template": {
"subject": "Email MFA App Verification Code",
"html": "<html><head></head><body><p>Here is the code: {{otp_code}}</p></body></html>",
"plain": "Here is the code: {{otp_code}}"
}
}
有没有更好的方法可以将带有空格和制表符的原始 JSON 传递到BrandTemplate
结构中而无需进行额外的转义或编组?我曾json.RawMessage
在其他情况下看到过这种用法,但如果可能的话,我想避免这种情况并直接使用BrandTemplate
结构。
任何关于此问题的建议或解决方案都将不胜感激!
在MarshalJSON方法中将字段转换
Template
为json.RawMessage。BrandTemplate
https://go.dev/play/p/cG8kPgltwvw