I assume you posted incorrect JSON and let's say it's '{"hello": "world"}
A struct has a predefined fields, and with arbitrary JSON coming in it's impossible to know ahead. The possible solution would be to convert it into a map.
var data interface{}
b := []byte(`{"hello": "world"}`)
err := json.Unmarshal(b, &data)
if err != nil {
panic(err)
}
fmt.Print(data)
As you print out the data, you'll probably get something like.
map[hello:world]
Which is in the form of map[string]interface{}
.
Then you can use type switch to loop into the map structure until you type assert all the interface{}
.
for k, v := range data.(map[string]interface{}) {
switch val := v.(type) {
case string:
v = val
default:
fmt.Println(k, "is unknown type")
}
}
Map is an ideal data structure when dealing with arbitrary incoming JSON. However, if the JSON is generated from an SQL table with predefined schemas, you can use a struct with the same structure instead of a map.
type Hello struct {
Hello string `json:"hello"`
}