So I'm trying to parse a JSON response. It can be multiple levels deep. This is what I did:
var result map[string]interface{} json.Unmarshal(apiResponse, &result)
Firstly, is this the right way to do it?
Lets say the response was as follows:
{ "args": { "foo": "bar" } }
To access key foo
, I saw a playground doing this:
result["args"].(map[string]interface{})["foo"]
Here, what is the .()
notation? Is this correct?
Golang Create Nested MapWe start by setting the data type of the key (top-level map) and the type of the value. Since this is a nested map, the value of the top-level map is a map. The previous code creates a simple restaurant menu using nested maps. In the first map, we set the data type as an int.
In Go language, a map is a powerful, ingenious, and versatile data structure. Golang Maps is a collection of unordered pairs of key-value. It is widely used because it provides fast lookups and values that can retrieve, update or delete with the help of keys. It is a reference to a hash table.
The notation x.(T)
is called a Type Assertion.
For an expression
x
of interface type and a typeT
, the primary expressionx.(T)
asserts thatx
is notnil
and that the value stored inx
is of typeT
.
Your example:
result["args"].(map[string]interface{})["foo"]
It means that the value of your results
map associated with key "args"
is of type map[string]interface{}
(another map with string
keys and any values). And you want to access the element of that map associated with the key "foo"
.
If you know noting about the input JSON format, then yes, you have to use a generic map[string]interface{}
type to process it. If you know the exact structure of the input JSON, you can create a struct
to match the expected fields, and doing so you can unmarshal a JSON text into a value of your custom struct
type, for example:
type Point struct { Name string X, Y int } func main() { in := `{"Name":"center","X":2,"Y":3}` pt := Point{} json.Unmarshal([]byte(in), &pt) fmt.Printf("Result: %+v", pt) }
Output:
Result: {Name:center X:2 Y:3}
Try it on the Go Playground.
Your current JSON input could be modelled with this type:
type Data struct { Args struct { Foo string } }
And accessing Foo
(try it on the Go Playground):
d := Data{} json.Unmarshal([]byte(in), &d) fmt.Println("Foo:", d.Args.Foo)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With