Thursday, June 8, 2023

How To Convert Array of Escaped Object String to String Object In Go Language

In our previous post we have learn how to convert the array/list of string objects into map and now with help of this map we can convert the array of objects in string format single object string.

Source Code:

package main

import (
	"encoding/json"
	"fmt"
)

type GenericHeader struct {
	Key   string `json:"key"`
	Value string `json:"value"`
}

func main() {

	escapeJsonString := "[{\"value\":\"123456\",\"key\":\"hash-key\"},
        {\"value\":\"srinivas4sfdc\",\"key\":\"requesting-host\"},
        {\"value\":\"token-based-authorization-policy\",\"key\":\"policy-name\"},
        {\"value\":\"application/x-www-form-urlencoded\",\"key\":\"Content-Type\"}]"
	fmt.Println("Input data:", string(escapeJsonString))
	var headers []GenericHeader
	err := json.Unmarshal([]byte(escapeJsonString), &headers)
	if err != nil {
		fmt.Println("Error:", err)
		return
	}

	headerMap := make(map[string]string)
	for _, header := range headers {
		fmt.Println(header.Key + ".." + header.Value)
		headerMap[header.Key] = header.Value
	}

	fmt.Println("Final Map Data==>", headerMap)
	marshalData, err := json.Marshal(headerMap)
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	fmt.Println("marshalData==>", marshalData)
	fmt.Println("Final Object String ==>", string(marshalData))
}

Input Data String:

"[{\"value\":\"123456\",\"key\":\"hash-key\"},{\"value\":\"srinivas4sfdc\",\"key\":\"requesting-host\"},{\"value\":\"token-based-authorization-policy\",\"key\":\"policy-name\"},{\"value\":\"application/x-www-form-urlencoded\",\"key\":\"Content-Type\"}]"

Output Data String:

{"Content-Type":"application/x-www-form-urlencoded","hash-key":"123456","policy-name":"token-based-authorization-policy","requesting-host":"srinivas4sfdc"}



Please comment or write us if you have any queries/requirements.

Please like,follow,bookmark,subscribe this site to receive daily updates.


FaceBook Page - I Love Coding. You?


Hope this helps you..Enjoy..!

No comments:

Post a Comment