I have the following structs, which I use to communicate with an API:
type Object struct {
Id uint64
Type string
Class string
Properties []Property
}
type Property struct {
Name string
DataType string
Value interface{}
}
And I use json.MarshalIndent()
to convert my struct into a json before sending it. this gives me something like:
{
"Id": 15,
"Type": "Node",
"Class": "Persona",
"Properties": [
{
"Name": "Nombre",
"DataType": "text",
"Value": "Oso"
},
{
"Name": "Edad",
"DataType": "int",
"Value": 45
},
{
"Name": "Fecha de Naciemiento",
"DataType": "date",
"Value": "1989-09-27T05:30:08-06:00"
}
]
}
I want to format the value
value (because it is of type interface{}
I need to format it depending on the value type) of the struct Property before marshaling it.
The first solution that occurred to me was to create a (Object) encode() string
function or something, that iterates through []Property
formatting the values, and marshaling each property separately, then reconstructing the Object with an []string
instead of the []Property
and then marshaling the object.
Is there any built-in way of doing this? If not, is there any idiomatic way of doing it?