I have a struct
type MyStruct struct {
A string
B int
C string
D int
}
And I want to convert it into a json object like this:
{
"A": "Some string",
"B": 1234,
"otherStruct": {
"C": "Other string",
"D": 5678
}
}
What json tags do I need to use to convert it properly?
I tried to add some json tags like this:
type MyStruct struct {
A string `json:"A"`
B int `json:"B"`
C string `json:"otherStruct.C"`
D int `json:"otherStruct.D"`
}
But it results in this:
{
"A": "Some string",
"B": 1234,
"otherStruct.C": "Other string",
"otherStruct.D": 5678
}
2
Answers
If you want this JSON output using the standard Go JSON package:
Then you will need to rewrite your Go structures to match the structure of the JSON. E.g:
This will produce:
I don’t believe there’s any way with the standard tooling to have the structure of the JSON be different from the structure of your variables.
While @larsks answer will work for you. Another option is to define a struct inside another struct.
But than you have to assign values to nested struct separately.
This will give you same output: