-2

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 \n 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 \n'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.

kostix
  • 51,517
  • 14
  • 93
  • 176
Allen Fisher
  • 607
  • 2
  • 7
  • 28
  • What have you tried? Include your code. What problems did you encounter? – Jonathan Hall May 25 '19 at 13:22
  • 3
    This is a slightly peculiar problem. Are newlines the only thing that need to be converted? Are you sure you don't just need to properly escape the entire string into whatever format you need? – Jonathan Hall May 25 '19 at 13:24
  • 1
    @Flimzy it was indeed just the newlines. This data is part of a bigger JSON blob that needed to be one value in a key-value pair – Allen Fisher May 26 '19 at 10:30
  • So what if that data has a literal `\n` string in it? You don't want to escape that? – Jonathan Hall May 26 '19 at 19:56

2 Answers2

2

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, "\n", `\n`)
    fmt.Println(s)
}

Playground: https://play.golang.org/p/lKZw78yOuMc

Output:

"project": {
  "uri": "/project/87",
  "name": "Allen's Test"
},
"project": {\n  "uri": "/project/87",\n  "name": "Allen's Test"\n},

For before Go 1.12, write:

s = strings.Replace(s, "\n", `\n`, -1)
peterSO
  • 158,998
  • 31
  • 281
  • 276
  • 1
    Thanks. This is what I ended up doing. Not quite sure why it wasn't working when I first tried it, but this is exactly what I needed. Thanks also for the before Go 1.12 piece. My build boxes are still on 1.11. – Allen Fisher May 26 '19 at 10:22
1

I have a feeling this is an XY problem...

but to simply replace a newline byte '\n' with a 2-char string \n, use:

strings.ReplaceAll(data, "\n", "\\n")

Playground: https://play.golang.org/p/Xmg4pgqFy5O

Output:

{"name": 2019-05-25,\n"tracker": {\n"project": {\n  "uri": "/project/87",\n ....

Note: this does not handle other formatting characters such as tab (\t) carriage-return (\r) etc.

colm.anseo
  • 19,337
  • 4
  • 43
  • 52