Remove escape character from json

Dear Team,

How to remove escape characters from json .

func myapi(ctx *gin.Context) {
_in := mystructure{}

err := ctx.ShouldBindJSON(&_in)

    before pass this function we want to remove the escape string from the json "VALUE"
data, err := services.MyServicefunction(_in)
if err != nil {
	ctx.JSON(http.StatusBadRequest, gin.H{"exception": err.Error()})
            return
} 
ctx.JSON(http.StatusOK, gin.H{"exception": "", "data": data})

}

Can you please show an example JSON and what you want to have removed?

in my json value we are getting “\n” “\r” “\t” character

example := {
data : "jhon \r \t \n "
}

we are passing same json to mysql store procedure . before send json to store procedure we would like clean these character from json value

Thanks Team. It is done.

Could you share you solution? I believe other memebers of the community could benefit from it as well.

1 Like

I have written following function : Replaceunwantcharacters

func myapi(ctx *gin.Context) {
_in := mystructure{}
err := ctx.ShouldBindJSON(&_in)

before pass this function we want to remove the escape string from the json "VALUE"

_in.fieldname = Replaceunwantcharacters(_in.fieldname )
data, err := services.MyServicefunction(_in)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{“exception”: err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{“exception”: “”, “data”: data})

}
func Replaceunwantcharacters(_in string) (_out string) {
_in = strings.ReplaceAll(_in, “\n”, “”)
_in = strings.ReplaceAll(_in, “\r”, “”)
_in = strings.ReplaceAll(_in, “\t”, “”)

return _in

}

You can accomplish this in an arguably easier and more performant (though performance is almost certainly not an issue and I would hate to be accused of premature optimization) way using a string replacer:

package main

import (
	"fmt"
	"strings"
)

func main() {
	testStr := "jhon\r\t\n"
	// Replacer to replace all unwanted characters
	r := strings.NewReplacer("\n", "", "\r", "", "\t", "")
	fmt.Println(r.Replace(testStr))
}

Here’s a playground link. If you find having your strings on a single line harder to read than your strings.ReplaceAll implementation, you can separate them out like so:

r := strings.NewReplacer(
	"\n", "",
	"\r", "",
	"\t", "",
)

This also makes it obvious if you accidentally create an odd number of strings, in which case you will get an error.

1 Like

Excellent.

Yet another single-pass approach is to use regexp.ReplaceAll and the regular expression "[\n\r\t]".

I’m wondering though why do you want to remove newlines, tabs and carriage returns?

(Okay I fully understand the latter)

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.