parse json without knowing the structure in go

To parse JSON in Go when the structure is unknown beforehand, you can make use of the json.Unmarshal function with an empty interface{} as the target datatype. This will allow you to retrieve the unknown structure as a nested map[string]interface{}. Here is a sample code snippet to demonstrate this approach:

main.go
package main

import (
	"encoding/json"
	"fmt"
	"log"
)

func main() {
	// Example JSON with unknown structure
	data := []byte(`{
		"name": "Alice",
		"age": 25,
		"address": {
			"city": "New York",
			"state": "NY"
		}
	}`)

	// Unmarshal JSON to generic interface{}
	var result interface{}
	err := json.Unmarshal(data, &result)
	if err != nil {
		log.Fatal(err)
	}

	// Print result as nested map[string]interface{}
	fmt.Printf("%#v\n", result)
}
450 chars
30 lines

In this example, the data variable contains a sample JSON with an unknown structure. It is then parsed using json.Unmarshal and stored in the result variable of type interface{}. Finally, the result variable is printed using fmt.Printf to show its structure as a nested map[string]interface{}.

gistlibby LogSnag