I have an interesting problem to solve. Because of a tool that I have to talk to, I need to convert newlines to the literal string I have the following data
{"name": 2019-05-25,
"tracker": {
"project": {
"uri": "/project/87",
"name": "Allen's Test"
},
"uri": "/tracker/57483",
"name": "Tasks"
},
"description": "[{Table
||Stack
||Current Version
||New Version
||Changes
|common
|1.0.214
|1.0.214
|* blah - [#345|https://blah.com/345]
|workflow
|2.2.23
|2.2.23
|* [ES-12345] blah - [#1087|https://blah.com/1087]
}]",
"descFormat": "Wiki"}
so basically instead of a multiline string, I need to convert it to a single line string with 's where the tool on the backend will convert it. I'm using go and not quite sure where to start. I asssume I need raw strings, but many of the source bits are api calls that have the newlines built in.
Any help would be appreciated.
For example,
package main
import (
"fmt"
"strings"
)
func main() {
s := `"project": {
"uri": "/project/87",
"name": "Allen's Test"
},`
fmt.Println(s)
s = strings.ReplaceAll(s, "
", `
`)
fmt.Println(s)
}
Playground: https://play.golang.org/p/lKZw78yOuMc
Output:
"project": {
"uri": "/project/87",
"name": "Allen's Test"
},
"project": {
"uri": "/project/87",
"name": "Allen's Test"
},
For before Go 1.12, write:
s = strings.Replace(s, "
", `
`, -1)
I have a feeling this is an XY problem...
but to simply replace a newline byte ' ' with a 2-char string , use:
strings.ReplaceAll(data, "
", "\
")
Playground: https://play.golang.org/p/Xmg4pgqFy5O
Output:
{"name": 2019-05-25,
"tracker": {
"project": {
"uri": "/project/87",
....
Note: this does not handle other formatting characters such as tab (\t
) carriage-return () etc.