In this post, I'm going to explain how to parse JSON data with a field which can be either a string or number in Go.
Go has a great support for JSON. In many cases what you have to do is to define corresponding `struct`s to parse JSON.
Let's say we're dealing with a Web API provided by some other company. It gives us a series of name-value pairs in this format:
We can assume `name` is a string and `value` is a number. Thus, the corresponding `struct` will be like this:
Now we can parse the JSON like this:
Cool. Then suddenly you realize that `value` isn't always a number- it can be a string:
Now it's f'ed up. But no worries. We can handle this situation by making `Value` either string or number instead of just string:
Now we can handle a string-or-number JSON field.
This is based on my real life experience and now I'm seeing a case where `Value` can also be an object, which I don't know how to handle gracefully. Life is tough.