[Solved] Is there any convenient way to get JSON element without type assertion?


If you model your JSON object with a struct and you unmarshal into a value of that, then you don’t need those ugly indices and type assertions, you can simply refer to struct fields.
Note that you don’t have to be afraid of the response being complex, you only need to model the parts you intend to use. E.g. if the response is an object with a hundred fields but you only need 2, then create a struct containing only those 2 fields.

If you don’t want to model your JSON object (or can’t because it’s dynamic), then you may write a general utility function which gets a value based on the path (series of map keys and slice indices), which you can see in this answer: Taking a JSON string, unmarshaling it into a map[string]interface{}, editing, and marshaling it into a []byte seems more complicated then it should be

And last you may use 3rd party libs which already contain this helper functionality, such as https://github.com/icza/dyno (disclosure: I’m the author).

Using github.com/icza/dyno, it would look like this:

value, err := dyno.Get(response, "body", 4, "data", "uid")

0

solved Is there any convenient way to get JSON element without type assertion?