skip to Main Content

I have JSON like this: {"key1": "value1", n n "key2": "value2nwithnewline"}

I want:

  1. remove n n
  2. 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


  1. you can split and join

    package main

    import (
    "fmt"
    "strings"
    )

    func main() {
        jsonStr := `{"key1": "value1", n n "key2": "value2nwithnewline"}`
        split := strings.Split(jsonStr, "\n \n")
        cleaned := strings.Join(split, " ")
        fmt.Println(cleaned)
    }
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search