In GO unmarshaling JSON data into a map[string]interface{}
is a common way to dynamically parse JSON without a predefined structure. The encoding/json
package in Go is used for this purpose
- Import the
encoding/json
Package: This package contains the necessary functions to encode and decode JSON. - Define the JSON Data: This can be a string or a byte slice containing your JSON data.
- Declare a Variable to Hold the Unmarshaled Data: This is typically a variable of type
map[string]interface{}
, whereinterface{}
can hold any type of value. - Unmarshal the JSON Data: Use the
json.Unmarshal
function to parse the JSON data into your map.
package mainimport (
"encoding/json"
"fmt"
"log"
)
func main() {
// JSON data
jsonData := `{"name":"John", "age":30, "city":"New York"}`
// Map to hold the JSON data
var result map[string]interface{}
// Unmarshal the JSON into the map
err := json.Unmarshal([]byte(jsonData), &result)
if err != nil {
log.Fatal(err)
}
// Print the map
fmt.Println(result)
// Accessing data from the map
// Type assertion is needed as map returns interface{} type
name, ok := result["name"].(string)
if ok {
fmt.Println("Name:", name)
}
age, ok := result["age"].(float64) // JSON numbers are floats
if ok {
fmt.Println("Age:", age)
}
}