Handle arbritrary keys
yepher opened this issue · comments
First off thanks for making this tool. I've used it on several projects. One issue I've bumped into a few times now is:
Some services, use JSON where the keys are arbitrarily generated. Here is an example where I handle this in my own code.
Sample JSON input
{
"status": "success",
"response": {
"12345678": {
"dynamic": true,
"label": "My Label One",
"ip_address": "11.222.123.124"
},
"22345678": {
"dynamic": false,
"label": "My Label two",
"ip_address": "11.222.123.124"
}
}
}
In this case the keys "22345678" and "12345678" are dynamic. I am not a fan of this sort of data structure and would much prefer if they would have used an array. But I have no control over this third-party service.
It would be nice if there were a way to give a hint to json-to-go
so it would generate that as a map with a given object value.
Current Output
type AutoGenerated struct {
Status string `json:"status"`
Response struct {
Num12345678 struct {
Dynamic bool `json:"dynamic"`
Label string `json:"label"`
IPAddress string `json:"ip_address"`
} `json:"12345678"`
Num22345678 struct {
Dynamic bool `json:"dynamic"`
Label string `json:"label"`
IPAddress string `json:"ip_address"`
} `json:"22345678"`
} `json:"response"`
}
Preferred Output
It would be much better if the resulting structs would do something like this instead:
Response map[string]NetworkObject `json:"response"`
type NetworkObject struct {
Dynamic bool `json:"dynamic"`
Label string `json:"label"`
IPAddress string `json:"ip_address"`
}
type NetworksResponse struct {
Status string `json:"status"`
Response map[string]NetworkObject `json:"response"`
Error int `json:"error"`
ErrorMessage string `json:"error_message"`
}
Solution
With all this said I am not quite sure how to provide this sort of hint to json-to-go
. Maybe could use special key names or potentially provide a JSON array that contains a list of keys what should invoke this sort of behavior.
Maybe something like this "json2go_dynamic_keys":["12345678", "22345678"],
so the resulting input json would be this:
{
"json2go_dynamic_keys":["12345678", "22345678"],
"status": "success",
"response": {
"12345678": {
"dynamic": true,
"label": "My Label One",
"ip_address": "11.222.123.124"
},
"22345678": {
"dynamic": false,
"label": "My Label two",
"ip_address": "11.222.123.124"
}
}
}