0

This is the full code:

files, _ := ioutil.ReadDir("files")
for _, f := range files {
    input, err := ioutil.ReadFile("files/" + f.Name())
    lines := strings.Split(string(input), "\n")

    for i, _ := range lines {
        lines[i] = fmt.Sprintf("%v,", lines[i])
    }

    output := strings.Join(lines, "\n")
    err = ioutil.WriteFile("files/"+f.Name()+"fix", []byte(output), 0644)
    if err != nil {
        log.Fatalln(err)
    }
}

I assume it is because lines[i] must contain a newline byte at the end of the string.. I have tried to remove it but failed..

The files I load are just json files e.g.

line 1: { "foo":"bar","baz":null }

line 2: { "foo":"bar","baz":"quz" }

Where I am trying to add a comma to the end of all lines.. any help would be much appreciated

Just to make myself a little more clear, what I get now is:

{ "foo":"bar","baz":null }
,
{ "foo":"bar","baz":"quz" }
,

whereas what I want to get is:

{ "foo":"bar","baz":null },
{ "foo":"bar","baz":"quz" },
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
fisker
  • 979
  • 4
  • 18
  • 28
  • Print out the quoted strings or the raw byte data and see exactly what's happening at each step – JimB Mar 05 '17 at 16:11

2 Answers2

3

Is it possible that your JSON data is coming from Windows and actually contains /r/n rather than just /n?

You can see this behaviour using /r/n in this playground example:

package main

import (
    "fmt"
    "strings"
)

func main() {
    a := "test\r\nnewtest\r\ntest2"
    b := strings.Split(a, "\n")
    c := strings.Join(b, ",\n")
    fmt.Printf("%v", c)

}
Colin Stewart
  • 572
  • 3
  • 2
  • Thanks a lot, I can sadly only upvote since I accepted PieOhPah answer (seems both answers correctly fixed my problem) – fisker Mar 05 '17 at 18:03
3

Try trimming the line to clean up whatever trailing unicode code points it has:

import "strings"

// ...

for _, line := range lines {
        line = fmt.Sprintf("%v,", strings.Trim(line, " \r\n"))
}
Pandemonium
  • 7,724
  • 3
  • 32
  • 51