How do I parse json from a url into a multidimensional array without a struct?
Is this even possible to do in Go?
I've seen a lot of different answers on stack, and other sites. But not one without a struct.
How do I parse json from a url into a multidimensional array without a struct?
Is this even possible to do in Go?
I've seen a lot of different answers on stack, and other sites. But not one without a struct.
Of course this is possible in Go, however without using structs it can become quite cumbersome.
If you already know the depth of the resulting array, you can define your slice using the empty interface (e.g. for a depth of 3):
var decoded [][][]interface{}
If you don't know the depth, use a normal []interface{}
instead and combine it with type assertions.
After that, a normal json.Unmarshal
call will produce the desired result:
err := json.Unmarshal(respData, &decoded)
if err != nil {
panic(err)
}
Now let’s look at decoding JSON data into Go values. Here’s an example for a generic data structure.
byt := []byte(`{"num":6.13,"strs":["a","b"]}`)
We need to provide a variable where the JSON package can put the decoded data. This map[string]interface{} will hold a map of strings to arbitrary data types.
var dat map[string]interface{}
Here’s the actual decoding, and a check for associated errors.
if err := json.Unmarshal(byt, &dat); err != nil {
panic(err)
}
fmt.Println(dat)
In order to use the values in the decoded map, we’ll need to convert them to their appropriate type. For example here we convert the value in num to the expected float64 type.
num := dat["num"].(float64)
fmt.Println(num)
Accessing nested data requires a series of conversions.
strs := dat["strs"].([]interface{})
str1 := strs[0].(string)
fmt.Println(str1)
See: https://gobyexample.com/json
You can work with any types with type casting data.(your_type)