Go JSON: Struct Tags और Marshal को सही समझने की गाइड

2025-01-30

Go में JSON handling मुख्यतः struct और tags पर आधारित है। गलत tag या omitempty की गलत समझ से client-server mismatch होता है।

Struct tags

json:"name,omitempty" key naming और empty value omission नियंत्रित करता है; unexported fields ignore होते हैं।

type User struct {
  ID   int    `json:"id"`
  Name string `json:"name,omitempty"`
}

Unmarshal

interface{} में संख्या float64 बनती है; strict typing के लिए struct या json.Number चुनें।

json.RawMessage

Inner payload parsing को बाद में टालने के लिए उपयोगी, खासकर polymorphic payload में।

Marshal

Reflection-आधारित प्रक्रिया है; hot paths में alternate libraries पर विचार किया जा सकता है।