type Struct struct {
Value string `json:"value"`
Value1 string `json:"value_one"`
Nest Nested `json:"nest"`
}
type Nested struct {
Something string `json:"something"`
}
Desidero aggiungere elementi che non sono nelle definizioni di struct senza creare un altro tipo di struttura. Per esempioGolang modifica json senza struct
Struct.Extra1 = Nested{"yy"}
Struct.Nested.Extra2 = "zz"
che si tradurrà
{
"Value": "xx",
"Value1": "xx",
"Extra1": {
"Something", "yy"
},
"Nest": {
"Something": "xx",
"Extra2": "zz"
}
}
Soluzione1: ho pensato di aggiungere omitempty
per raggiungere questo obiettivo, ma rende il complesso strutture.
type Struct struct {
Value string
Value1 string
Nest Nested
Extra1 Nested `json:"omitempty"`
}
type Nested struct {
Something string
Extra2 string `json:"omitempty"`
}
Solution2:
myextras := make(map[string]interface{})
// get Struct.Nested in map[string]interface{} format
myextras = Struct.Nest
myextras["Extra2"] = "zz"
// get Struct in map[string]interface{} format
struct["Nest"] = myextras
struct["Extra1"] = Nested{"yy"}
// solves the problem with lots of type casting but doesn't support json tag naming
Esiste una soluzione migliore per aggiungere elementi annidati, che non sono rappresentate nel struct tipo di dati con il supporto di JSON-tag e potrebbero essere utilizzati per l'uscita per l'utente.
dal momento che la mia modifica perfettamente valida è stata respinta dai mods come "dovrebbe sii un commento "(anche se questo è un enorme spreco di spazio come commento) - nota che non hai bisogno di' json: "-" 'per evitare che la serializzazione sia extra, dal momento che non viene esportato. –
Grazie @NateFinch per le informazioni, ha senso. Lo sto modificando per conto di te. –