I have JSON like this: {"key1": "value1", n n "key2": "value2nwithnewline"}
I want:
- remove n n
- keep value2nwithnewline.
So I will have a valid JSON.
What I tried: regrex but failed figure out how to specify outside of key and value.
and this:
package main
import (
"bytes"
"fmt"
)
func main() {
jsonStr := `{"key1": "value1", n n "key2": "value2nwithnewline"}`
var cleaned bytes.Buffer
quoteCount := 0
for i := 0; i < len(jsonStr); i++ {
if jsonStr[i] == '"' {
quoteCount++
}
if quoteCount%2 == 0 && jsonStr[i] != 'n' {
cleaned.WriteByte(jsonStr[i])
} else if quoteCount%2 == 1 {
cleaned.WriteByte(jsonStr[i])
}
}
fmt.Println(cleaned.String())
}
Link to Go playground: https://go.dev/play/p/zvNSCuE4SjQ
This does not work because it can n
is actually
n
2
Answers
you can split and join
package main
import (
"fmt"
"strings"
)
Given the parameters of your question, you could replace all nn using
strings.ReplaceAll
:cleaned := strings.ReplaceAll(input, "\n \n ", "")
If you want to continue using your current strategy, there’s a few issues. One of them is that you’re always writing to the string, regardless of your condition:
cleaned.WriteByte(jsonStr[i])
happens in your if and else cases.