Put a JSON object into map[string]string directly in Go

This is an example Go program demonstrating reading a JSON object into a map from string to string, without using a struct to read the JSON in to.

package main

import (
        "encoding/json"
        "fmt"
)

var j = `{
"size":"medium",
"colour":"yellow",
"style":"nice"
}`

func main() {
        x := make(map[string]string)
        // Just to demonstrate how this works.
        x["monkey"] = "George"
        err := json.Unmarshal([]byte(j), &x)
        if err != nil {
                fmt.Printf("Error: %s\n", err)
                return
        }
        for key, value := range x {
                fmt.Printf("%s -> %s\n", key, value)
        }
}

(download)

The output of the example looks like this:

style -> nice
monkey -> George
size -> medium
colour -> yellow


Copyright © Ben Bullock 2009-2023. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (benkasminbullock@gmail.com) or use the discussion group at Google Groups. / Privacy / Disclaimer