Golang program to convert the hash collection into string


Golang has json package that is used for converting the hask collection into strin. A hashmap belongs to hash collection which stores the data as key:value pairs, whereas a string is a sequence of characters and it is immutable. In this article, we will use two examples to convert the hash collection into string. In the first example, the Json package will be used to convert the map to encoded byte array whereas in the second example sort package will be use along the loops.

Syntax

json.Marshal()

This function belongs to the JSON package and it converts the value provided to a JSON-encoded byte array.

func make ([] type, size, capacity)

The make function in go language is used to create an array/map it accepts the type of variable to be created, its size and capacity as arguments.

func len(v Type) int

The len() function is used to get the length of any parameter. It takes one parameter as the data type variable whose length we wish to find and returns the integer value which is the length of the variable.

Method 1:Using json Pacakge

In this example, a hashmap will be created which will be used by the json package in golang to convert it into encoded byte array which will be further converted to string using the string function. Let’s see the code and algorithm to know the process of execution.

Algorithm

  • Import the fmt package and the encoding/json package to fulfill the program’s requirements

  • Create a main function and inside the function create a hashmap with name hashcollection where keys and values both are of type string.

  • Then, use Marshal function from the json package to convert this map to a json-encoded byte array.

  • If any error is encountered while map is encoded print the error.

  • Then, convert the byte array to string using string function.

  • Print the hash collection after its converted to string.

  • The print statement is executed using Println function from the fmt package.

Example

In the following example, we are going to convert hash collection to string using json package.

//Golang program to convert the hash collection into string
package main
import (
   "encoding/json"
   "fmt"
)

//create a main function
func main() {
   hashCollection := map[string]string{ //create hashmap using map literal
      "item1": "value1",
      "item2": "value2",
      "item3": "value3",
   }

   hashCollectionJson, err := json.Marshal(hashCollection)
   if err != nil {
      panic(err)  //print if any error encountered
   }

   hash_string := string(hashCollectionJson) //convert the byte array to string
   fmt.Println("The hash collection after its converted to string:")
   fmt.Println(hash_string) //print the hash string
}

Output

The hash collection after its converted to string:
{"item1":"value1","item2":"value2","item3":"value3"}

Method 2: Using Sort Package

In this example, we will create a hashmap and a slice which will be iterated further to get the key:value pairs in the string. The entire string will be printed on the console. Let’s see through the code and the algorithm how it’s done.

Algorithm

  • Import the fmt and sort package in the program to fulfill the program’s requirements.

  • Create a hashmap using map literal in the main with keys and values both of the type string.

  • Create a keys named slice using the make built-in function with length similar to that of hashmap.

  • Initialize the i variable to 0 and iterate the hashmap till its range.

  • In every iteration add the keys of the hashmap in the keys slice and increment the index variable in every iteration.

  • Then, use the Strings method of sort package to sort the keys.

  • In this step, create a variable hashmap_string, add the key:value pairs in this string by iterating the keys slice

  • Print the string on the console using Println function where ln means new line.

Example

In the following example, we are going to use sort function to convert hash collection into string.

package main
import (
   "fmt"
   "sort"
)

//create a main function
func main() {
   hashmap := map[string]string{ //create a hashmap using map literal
      "key1": "value1",
      "key2": "value2",
      "key3": "value3",
   }
   keys := make([]string, len(hashmap)) //create keys slice to print the string 
   i := 0
   for k := range hashmap {
      keys[i] = k
      i++
   }
   sort.Strings(keys) //sort the keys slice

   var hashmap_string string
   for _, k := range keys {
      v := hashmap[k]
      hashmap_string += fmt.Sprintf("%s:%s,", k, v) //add the key:value pairs
   }
   hashmap_string = "{" + hashmap_string[:len(hashmap_string)-1] + "}"
   fmt.Println("The hash collection after converted to string is:")

   fmt.Println(hashmap_string)  //print the string
}

Output

The hash collection after converted to string is:
{key1:value1,key2:value2,key3:value3}

Conclusion

We executed and compiled the program of converting the hash collection to string using two examples. In the first example, we used json package and in the second example we used the sort package with the use of loops to get the desired output.

Updated on: 01-Mar-2023

561 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements