We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

map[string]interface{}

Sometimes you have to deal with JSON data of unknown or varying structure in Go. In those instances map[string]interface{} offers a flexible way to handle it without predefined structs.

Think about it: a JSON object is a key-value pair, where the key is a string and the value can be any JSON type. map[string]interface{} is a map where the key is a string and the value can be any Go type.

var data map[string]interface{}
jsonString := `{"name": "Alice", "age": 30, "address": {"city": "Wonderland"}}`
json.Unmarshal([]byte(jsonString), &data)
fmt.Println(data["name"])  // Output: Alice
fmt.Println(data["address"].(map[string]interface{})["city"])  // Output: Wonderland

any is an alias for interface{}

Assignment

A junior developer's deadline is looming. They've been tasked with creating functions to retrieve and log various resources from Jello's API. Rather than making multiple structs and type-safe functions, the junior developer has decided to make two flexible functions. Help them complete their task before their boss, Wayne Lagner, asks them to refactor it.

Complete the getResources and logResources functions.

getResources()

getResources takes a url string and returns a slice of maps []map[string]interface{} and an error.

It's a slice of maps because the API response is an array of JSON objects.

logResources()

logResources takes a slice of maps []map[string]interface{} and prints its keys and values to the console. Because maps are unsorted we will be adding formatted strings to a slice of strings []string which is then sorted.

You do not need to account for nested JSON objects. Assume they are neat key-value pairs, one level deep.

The output from one issue should look like this:

Issue:
Key: estimate - Value: 19
Key: id - Value: 0194fdc2-fa2f-4cc0-81d3-ff12045b73c8
Key: status - Value: TODO
Key: title - Value: Fix that one bug nobody understands