Golang Parse JSON with Simple Examples

In this post, we'll look at how to parse a JSON string for structured and unstructured data. We also handle the situation where the json string contains a backlash. In the previous post, I demonstrated how to parse a json file in Golang using the json package and Unmarshal() function. In golang, we also use this package to convert a json string to a struct. To better understand how it works, consider the following examples.

json package: Package json implements encoding and decoding of JSON as defined in RFC 7159. The mapping between JSON and Go values is described in the documentation for the Marshal and Unmarshal functions.

Advertisement

func Unmarshal(data []byte, v any) error: Unmarshal parses the JSON-encoded data and stores the result in the value pointed to by v. If v is nil or not a pointer, Unmarshal returns an InvalidUnmarshalError.

 

Example 1: Golang parse JSON to nested struct

Here is an example of parsing a json string to a nested struct data in Golang using the Unmarshal() function:

package main

import (
	"encoding/json"
	"fmt"
)

// declaring a struct
type Squad struct {
	SquadName string `json:"squadName"`
	Formed    int    `json:"formed"`
	Leader    string `json:"leader"`
	Status    bool   `json:"active"`
	Members   []struct {
		Name           string `json:"name"`
		Age            int    `json:"age"`
		SecretIdentity string `json:"secretIdentity"`
	} `json:"members"`
}

// main function
func main() {

	// defining a struct instance
	var squad Squad

	// string json
	jsonString := `{
		"squadName": "Go Linux Cloud",
		"formed": 2022,
		"leader": "",
		"active": true,
		"members": [
		  {
			"name": "Anna",
			"age": 30,
			"secretIdentity": "Duke"
		  },
		  {
			"name": "Harry Potter",
			"age": 32,
			"secretIdentity": "Jane"
		  }]}`

	// decoding squad struct from json string
	err := json.Unmarshal([]byte(jsonString), &squad)

	if err != nil {
		// print out if error is not nil
		fmt.Println(err)
	}

	// printing details of struct
	fmt.Println("Struct is:", squad)
	fmt.Println("Squad's name is:", squad.SquadName)
	fmt.Println("Squad's leader is:", squad.Leader)
	fmt.Println("1st member is:", squad.Members[0].Name)
}

Output:

Squad's name is: Go Linux Cloud
Squad's leader is:
1st member is: Anna

 

Example 2: Golang parse JSON to map

In some cases, we do not know the structure of your JSON properties beforehand, so we cannot define structs to unmarshal our data. To deal with these cases we have to create a map of strings to empty interfaces. Let's take a look at the below example:

package main

import (
	"encoding/json"
	"fmt"
)

// main function
func main() {

	// defining a map
	var result map[string]interface{}

	// string json
	jsonString := `{
		"results": [
		  {
			"nameChunk1": [
			  {
				"name1": "Anna",
				"name2": "Bob"
			  }
			],
			"nameChunk2": [
			  {
				"name1": "Clay",
				"name2": "Dean"
			  }
			]
		  }
		],
		"author": "Go Linux Cloud"
	  }`

	err := json.Unmarshal([]byte(jsonString), &result)

	if err != nil {
		// print out if error is not nil
		fmt.Println(err)
	}

	// printing details of map
	// iterate through the map
	for key, value := range result {
		fmt.Println(key, ":", value)
	}
}

Output:

results : [map[nameChunk1:[map[name1:Anna name2:Bob]] nameChunk2:[map[name1:Clay name2:Dean]]]]
author : Go Linux Cloud

 

Example 3: Golang parse JSON string with backslash

Using strconv.Unquote() function

func Unquote(s string) (string, error): Unquote interprets s as a single-quoted, double-quoted, or backquoted Go string literal, returning the string value that s quotes. (If s is single-quoted, it would be a Go character literal; Unquote returns the corresponding one-character string.)

Advertisement

Here is an example of parsing this string "{\"channel\":\"buu\",\"sender\":\"anna\", \"receiver\":\"bob\", \"message\":\"hello\"}" to a string map.

package main

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

// main function
func main() {

	// defining a map
	var result map[string]interface{}

	// string json
	jsonString := `"{\"channel\":\"buu\",\"sender\":\"anna\", \"receiver\":\"bob\", \"message\":\"hello\"}"`
        // replace \ with empty character
	s, _ := strconv.Unquote(string(jsonString))
	err := json.Unmarshal([]byte(s), &result)

	if err != nil {
		// print out if error is not nil
		fmt.Println(err)
	}

	// printing details of map
	// iterate through the map
	for key, value := range result {
		fmt.Println(key, ":", value)
	}
}

Output when we iterate through the map:

sender : anna
receiver : bob
message : hello
channel : buu

 

Using Replace() function

func Replace(s, old, new string, n int) string: Replace returns a copy of the string s with the first n non-overlapping instances of old replaced by new

In this example, we will replace backslash with empty character and then parse it like a normal json string:

package main

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

// main function
func main() {

	// defining a map
	var result map[string]interface{}

	// string json
	jsonString := `"{\"channel\":\"buu\",\"sender\":\"anna\", \"receiver\":\"bob\", \"message\":\"hello\"}"`
	jsonString = strings.Replace(jsonString, "\\", "", -1)
	jsonString = jsonString[1 : len(jsonString)-1]

	err := json.Unmarshal([]byte(jsonString), &result)

	if err != nil {
		// print out if error is not nil
		fmt.Println(err)
	}

	// printing details of map
	// iterate through the map
	for key, value := range result {
		fmt.Println(key, ":", value)
	}
}

The output will be the same with example 3.

 

Summary

The above examples demonstrate how to read a json string using the golang Unmarshal() function. If your json string contains a backslash, you can use Replace() or Unquote() function.

 

References

https://www.json.org/json-en.html
https://pkg.go.dev/encoding/json
https://pkg.go.dev/strings#Replace

 

Categories GO

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment

X