Loading JSON string in Go

Golang provides great set of standard libraries to work with multiple use cases we encounter while developing software. In this blog, we will look at one of the most common use cases to load JSON data into memory of Go runtime.

Code Snippet

We will make use of Go standard library encoding/json to load JSON string to memory. There are two ways to do so,

  • Into a well defined structure variable.
  • Into a generic map.

Here’s the snippet loading same string in two different ways as mentioned above.

package main

import (
	"encoding/json"
	"fmt"
)

// Mobile structure with well defined properties.
type Mobile struct {
	Model        string `json:"model"`
	Manufacturer string `json:"manufacturer"`
	Price        int    `json:"price"`
	Currency     string `json:"currency"`
}

func main() {
	// JSON string
	s1 := `{
		"model": "S20 FE",
		"manufacturer": "Samsung",
		"price": 45000,
		"currency": "INR"
		}`
	// Loading JSON into a well defined structure variable.
	var mobile Mobile
	err := json.Unmarshal([]byte(s1), &mobile)
	if err != nil {
		fmt.Println("Error unmarshalling!" + err.Error())
		return
	}
	fmt.Println("Successfully loaded JSON string into a well defined structure variable in memory")
	fmt.Printf("Details:\n%+v", mobile)
	// Loading JSON into a generic map.
	var data map[string]interface{}
	err = json.Unmarshal([]byte(s1), &data)
	if err != nil {
		fmt.Println("Error unmarshalling!" + err.Error())
		return
	}
	fmt.Println("\nSuccessfully loaded JSON into generic map in memory")
	fmt.Printf("Details:\n%v", data)
}

Snippet also available at: Go repository on Hello World.

Output

That’s it for the blog! We will keep writing more of these short blogs. So until then, keep learning. Cheers ✌️

Leave a comment

Design a site like this with WordPress.com
Get started