How to automatically add type field in JSON in Go?

How to add type field automatically for every serialized JSON in Go?

For example, in this code:

 type Literal struct { Value interface{} `json:'value'` Raw string `json:'raw'` } type BinaryExpression struct { Operator string `json:"operator"` Right Literal `json:"right"` Left Literal `json:"left"` } os.Stdout.Write(json.Marshal(&BinaryExpression{ ... })) 

Instead of creating something like:

 { "operator": "*", "left": { "value": 6, "raw": "6" }, "right": { "value": 7, "raw": "7" } } 

I would like to generate this:

 { "type": "BinaryExpression", "operator": "*", "left": { "type": "Literal", "value": 6, "raw": "6" }, "right": { "type": "Literal", "value": 7, "raw": "7" } } 
+5
source share
1 answer

You can override the MarshalJSON function for your structure to introduce the type in the auxiliary structure, which is then returned.

 package main import ( "encoding/json" "os" ) type Literal struct { Value interface{} `json:'value'` Raw string `json:'raw'` } func (l *Literal) MarshalJSON() ([]byte, error) { type Alias Literal return json.Marshal(&struct { Type string `json:"type"` *Alias }{ Type: "Literal", Alias: (*Alias)(l), }) } type BinaryExpression struct { Operator string `json:"operator"` Right Literal `json:"right"` Left Literal `json:"left"` } func (b *BinaryExpression) MarshalJSON() ([]byte, error) { type Alias BinaryExpression return json.Marshal(&struct { Type string `json:"type"` *Alias }{ Type: "BinaryExpression", Alias: (*Alias)(b), }) } func main() { _ = json.NewEncoder(os.Stdout).Encode( &BinaryExpression{ Operator: "*", Right: Literal{ Value: 6, Raw: "6", }, Left: Literal{ Value: 7, Raw: "7", }, }) } 
+4
source

All Articles