Unmarshal the JSON data into a map[string]interface{} in GO (2024)

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

  1. Import the encoding/json Package: This package contains the necessary functions to encode and decode JSON.
  2. Define the JSON Data: This can be a string or a byte slice containing your JSON data.
  3. Declare a Variable to Hold the Unmarshaled Data: This is typically a variable of type map[string]interface{}, where interface{} can hold any type of value.
  4. Unmarshal the JSON Data: Use the json.Unmarshal function to parse the JSON data into your map.
package main

import (
"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)
}
}

Unmarshal the JSON data into a map[string]interface{} in GO (2024)
Top Articles
Latest Posts
Article information

Author: Mrs. Angelic Larkin

Last Updated:

Views: 5511

Rating: 4.7 / 5 (67 voted)

Reviews: 82% of readers found this page helpful

Author information

Name: Mrs. Angelic Larkin

Birthday: 1992-06-28

Address: Apt. 413 8275 Mueller Overpass, South Magnolia, IA 99527-6023

Phone: +6824704719725

Job: District Real-Estate Facilitator

Hobby: Letterboxing, Vacation, Poi, Homebrewing, Mountain biking, Slacklining, Cabaret

Introduction: My name is Mrs. Angelic Larkin, I am a cute, charming, funny, determined, inexpensive, joyous, cheerful person who loves writing and wants to share my knowledge and understanding with you.