Go Playbook

Course › Week 3 · Real data and speed › Day 6 · lesson 20 of 42 · 40 min reading + 2–3 h practice

Build csv2json

100K survey rows to JSON Lines with validation, benchmarked against PHP.

encoding/csvencoding/jsonbenchmark

On this page
  1. The task
  2. The plan
  3. Step 1: one answer
  4. Step 2: the loop
  5. Step 3: test the conversion
  6. Step 4: main and the files
  7. The benchmark: the same tool in PHP
  8. Calling it from Laravel
  9. Practice
  10. Remember

Today’s tool uses everything this week taught: CSV read one record at a time, JSON written one line at a time, structured logs, closures, and errors that say where they happened. It turns a school-evaluation export into JSON Lines for an analysis pipeline, and lists every row it rejects.

Then the question every Go lesson for a PHP developer has to answer: is it worth it? The same tool in PHP, on the same input, measured on the same machine.

#dataTuesday 11:40

Sara · dataThe weekly evaluation export is over a million answers now. The Laravel import job reads it with collect(), hits the memory limit at about 600K rows, and when it does finish, a few bad rows have quietly become score 0.

Sara · dataWhat the analysis pipeline wants: JSON Lines, comments cleaned (lower-case, no punctuation, and Arabic must survive), and every rejected row listed with its line number so the schools can fix their data. And it must accept the file straight from Excel.

The plan

csv2json/
csv2json/
├── go.mod            (module github.com/you/csv2json)
├── main.go           (flags, files, logs, exit codes)
├── answer.go         (the header, one answer: checked and cleaned)
├── convert.go        (the loop: CSV in, JSON Lines and rejected rows out)
└── convert_test.go

The same shape as logstat v2: convert takes an io.Reader and two io.Writers, so the whole conversion is tested with strings, and main only deals with the outside world. Here is the sample this page runs on: an Excel export (with the byte order mark), with a word for a score, a score of 9, a short row, a multi-line comment and Arabic.

survey.csv
evaluation_id,school,question,score,comment
1001,Alexandria STEM,Q1,5,Clear explanations
1001,Alexandria STEM,Q2,4,
1002,Cairo Language School,Q1,3,"Too  FAST!!"
1002,Cairo Language School,Q2,five,
1003,Giza Primary,Q1,9,
1003,Giza Primary,Q2,2,"Needs more examples,
and a slower pace"
1004,Luxor Prep
1005,Aswan Secondary,Q1,4,"شرح واضح جدا، شكرا"

Step 1: one answer

The header

findColumns is the column check from the CSV lesson, with the byte order mark removed. The positions are kept in a small struct instead of a map, so clean reads c.score and a typo is a compile error. The wanted table pairs each column name with a pointer to its field (the pointers lesson), and the loop fills them through *w.field = i.

Checking and cleaning

clean returns an Answer or an error that says why the row was rejected, in words a school can act on. field is a closure over record (the closures lesson), so each field is trimmed in one place.

The comment is cleaned with strings.FieldsFunc, which splits a string wherever the function returns true: here at every character that is neither a letter nor a digit. The unicode package knows letters in every script, so Arabic survives and !! disappears. Comment is a *string (the JSON lesson): no words means null in the JSON, not "".

csv2json/answer.gonew file
package main

import (
	"errors"
	"fmt"
	"strconv"
	"strings"
	"unicode"
)

// columns is where each column csv2json needs sits in the header.
type columns struct {
	evaluationID, school, question, score, comment int
}

// findColumns reads the header. It removes the byte order mark that Excel writes at the start of a
// "CSV UTF-8" file, so an export straight from Excel works.
func findColumns(header []string) (columns, error) {
	positions := map[string]int{}
	for i, name := range header {
		if i == 0 {
			name = strings.TrimPrefix(name, "\ufeff")
		}
		positions[strings.TrimSpace(name)] = i
	}

	var c columns
	wanted := []struct {
		name  string
		field *int
	}{
		{"evaluation_id", &c.evaluationID},
		{"school", &c.school},
		{"question", &c.question},
		{"score", &c.score},
		{"comment", &c.comment},
	}
	for _, w := range wanted {
		i, ok := positions[w.name]
		if !ok {
			return columns{}, fmt.Errorf("the header has no %q column", w.name)
		}
		*w.field = i
	}
	return c, nil
}

// Answer is one cleaned answer, as written to the JSON Lines output.
type Answer struct {
	EvaluationID int     `json:"evaluation_id"`
	School       string  `json:"school"`
	Question     string  `json:"question"`
	Score        int     `json:"score"`
	Comment      *string `json:"comment"`
	Words        int     `json:"words"`
}

// clean checks one record and returns its answer, or the reason it was rejected.
func clean(record []string, c columns) (Answer, error) {
	field := func(i int) string { return strings.TrimSpace(record[i]) }

	id, err := strconv.Atoi(field(c.evaluationID))
	if err != nil || id < 1 {
		return Answer{}, fmt.Errorf("evaluation_id %q is not a positive number", field(c.evaluationID))
	}
	score, err := strconv.Atoi(field(c.score))
	if err != nil {
		return Answer{}, fmt.Errorf("score %q is not a number", field(c.score))
	}
	if score < 1 || score > 5 {
		return Answer{}, fmt.Errorf("score %d is outside 1 to 5", score)
	}
	school := field(c.school)
	if school == "" {
		return Answer{}, errors.New("school is empty")
	}
	question := field(c.question)
	if !isQuestionID(question) {
		return Answer{}, fmt.Errorf("question %q is not like Q1", question)
	}

	// The comment, lower-case, with every run of characters that are not letters or digits turned
	// into one space: "Too  FAST!!" becomes "too fast". Arabic letters are letters too.
	words := strings.FieldsFunc(strings.ToLower(field(c.comment)), func(r rune) bool {
		return !unicode.IsLetter(r) && !unicode.IsNumber(r)
	})
	answer := Answer{EvaluationID: id, School: school, Question: question, Score: score, Words: len(words)}
	if len(words) > 0 {
		comment := strings.Join(words, " ")
		answer.Comment = &comment
	}
	return answer, nil
}

// isQuestionID reports whether s looks like Q1, Q2 … Q10.
func isQuestionID(s string) bool {
	if len(s) < 2 || s[0] != 'Q' {
		return false
	}
	for _, r := range s[1:] {
		if r < '0' || r > '9' {
			return false
		}
	}
	return true
}

Step 2: the loop

Three outputs, each buffered, each flushed with its error checked at the end: the JSON Lines through a bufio.Writer (without it, every line would be a separate write to the operating system, which is slow for a million lines), and the rejected rows through a csv.Writer.

A *csv.ParseError is a rejected row, not a failure (the CSV lesson): its StartLine is the row’s first line, and its Err is the reason without the line number in front. Any other read error stops the conversion. Every error from the loop is wrapped with what was being done.

csv2json/convert.gonew file
package main

import (
	"bufio"
	"encoding/csv"
	"encoding/json/jsontext"
	"encoding/json/v2"
	"errors"
	"fmt"
	"io"
	"strconv"
)

// summary counts what one conversion did.
type summary struct {
	Rows     int
	Written  int
	Rejected int
}

// convert reads survey answers as CSV from in, writes each valid answer as one line of JSON to out,
// and each rejected row, with its line number and the reason, as a CSV row to rejects. A rejected
// row never stops the conversion; a failure to read or write does.
func convert(in io.Reader, out io.Writer, rejects io.Writer) (summary, error) {
	var s summary
	reader := csv.NewReader(in)
	header, err := reader.Read()
	if err != nil {
		return s, fmt.Errorf("reading the header: %w", err)
	}
	cols, err := findColumns(header)
	if err != nil {
		return s, err
	}

	buffered := bufio.NewWriter(out)
	encoder := jsontext.NewEncoder(buffered)
	rejected := csv.NewWriter(rejects)
	if err := rejected.Write([]string{"line", "reason"}); err != nil {
		return s, fmt.Errorf("writing the rejected rows: %w", err)
	}

	for {
		record, err := reader.Read()
		if errors.Is(err, io.EOF) {
			break
		}
		var line int
		var parseErr *csv.ParseError
		switch {
		case errors.As(err, &parseErr):
			line, err = parseErr.StartLine, parseErr.Err // "wrong number of fields", a broken quote
		case err != nil:
			return s, fmt.Errorf("reading the CSV: %w", err)
		default:
			line, _ = reader.FieldPos(0)
		}
		s.Rows++

		var answer Answer
		if err == nil {
			answer, err = clean(record, cols)
		}
		if err != nil {
			s.Rejected++
			if err := rejected.Write([]string{strconv.Itoa(line), err.Error()}); err != nil {
				return s, fmt.Errorf("writing the rejected rows: %w", err)
			}
			continue
		}
		if err := json.MarshalEncode(encoder, answer); err != nil {
			return s, fmt.Errorf("writing the answer on line %d: %w", line, err)
		}
		s.Written++
	}

	rejected.Flush()
	if err := rejected.Error(); err != nil {
		return s, fmt.Errorf("writing the rejected rows: %w", err)
	}
	if err := buffered.Flush(); err != nil {
		return s, fmt.Errorf("writing the output: %w", err)
	}
	return s, nil
}

Step 3: test the conversion

One test runs the whole conversion on a string with every problem at once: a reordered header with a byte order mark, a multi-line comment, a bad score, a short row and an empty school. It checks the summary, the exact JSON line and the exact rejected rows. summary{…} in parentheses is needed in an if with a short statement, so that the braces are not read as the start of the block.

The second test checks that a header without score stops with an error that names the column.

csv2json/convert_test.gonew file
package main

import (
	"strings"
	"testing"
)

func TestConvert(t *testing.T) {
	input := "\ufeffschool,evaluation_id,question,score,comment\n" +
		"Giza Primary,1003,Q1,5,\"Very GOOD,\nthank you\"\n" +
		"Giza Primary,1003,Q2,five,\n" +
		"Luxor Prep,1004\n" +
		",1005,Q1,4,\n"

	var out, rejects strings.Builder
	got, err := convert(strings.NewReader(input), &out, &rejects)
	if err != nil {
		t.Fatalf("convert returned an error: %v", err)
	}

	if want := (summary{Rows: 4, Written: 1, Rejected: 3}); got != want {
		t.Errorf("summary = %+v, want %+v", got, want)
	}
	wantOut := `{"evaluation_id":1003,"school":"Giza Primary","question":"Q1","score":5,"comment":"very good thank you","words":4}` + "\n"
	if out.String() != wantOut {
		t.Errorf("output =\n%s\nwant\n%s", out.String(), wantOut)
	}
	wantRejects := "line,reason\n" +
		"4,\"score \"\"five\"\" is not a number\"\n" +
		"5,wrong number of fields\n" +
		"6,school is empty\n"
	if rejects.String() != wantRejects {
		t.Errorf("rejects =\n%s\nwant\n%s", rejects.String(), wantRejects)
	}
}

func TestConvertRejectsAHeaderWithoutScore(t *testing.T) {
	var out, rejects strings.Builder
	_, err := convert(strings.NewReader("evaluation_id,school,question,comment\n"), &out, &rejects)
	if err == nil || !strings.Contains(err.Error(), `"score"`) {
		t.Errorf("convert error = %v, want one that names the score column", err)
	}
}
$ go test -v
=== RUN   TestConvert
--- PASS: TestConvert (0.00s)
=== RUN   TestConvertRejectsAHeaderWithoutScore
--- PASS: TestConvertRejectsAHeaderWithoutScore (0.00s)
PASS
ok  	github.com/you/csv2json	0.003s

Step 4: main and the files

Writing a file

os.Create makes a file for writing (or empties an existing one). Unlike a file you only read, a file you write must be closed with its error checked: the operating system may report a full disk or a failed network drive only at Close. run closes the errors file itself instead of defer, so that it can return that error. This is the case logstat v1 set aside.

The rejected rows go to stderr when no -errors file is given, so they are never lost. -max-rejected turns “half the file was bad” into a failure, exit code 1, instead of a quietly smaller output.

csv2json/main.gonew file
package main

import (
	"flag"
	"fmt"
	"io"
	"log/slog"
	"os"
)

func main() {
	errorsPath := flag.String("errors", "", "write the rejected rows, with their line and reason, to this CSV file instead of stderr")
	maxRejected := flag.Float64("max-rejected", 5, "fail when more than this percentage of rows is rejected")
	flag.Usage = func() {
		fmt.Fprintln(flag.CommandLine.Output(), "usage: csv2json [-errors FILE] [-max-rejected PERCENT] <survey.csv> > answers.jsonl")
		flag.PrintDefaults()
	}
	flag.Parse()
	if flag.NArg() != 1 {
		flag.Usage()
		os.Exit(2)
	}
	logger := slog.New(slog.NewTextHandler(os.Stderr, nil))

	s, err := run(flag.Arg(0), *errorsPath, os.Stdout)
	if err != nil {
		logger.Error("conversion failed", "err", err)
		os.Exit(1)
	}
	logger.Info("converted", "rows", s.Rows, "written", s.Written, "rejected", s.Rejected)

	if s.Rows > 0 && float64(s.Rejected)*100/float64(s.Rows) > *maxRejected {
		logger.Error("too many rejected rows: check the export before using the output", "max_percent", *maxRejected)
		os.Exit(1)
	}
}

// run opens the files and converts. The rejected rows go to errorsPath, or to stderr when it is "".
func run(inputPath, errorsPath string, out io.Writer) (summary, error) {
	in, err := os.Open(inputPath)
	if err != nil {
		return summary{}, err
	}
	defer in.Close()

	if errorsPath == "" {
		return convert(in, out, os.Stderr)
	}
	errorsFile, err := os.Create(errorsPath)
	if err != nil {
		return summary{}, err
	}
	s, err := convert(in, out, errorsFile)
	// A file that was written must be closed with its error checked: Close is where a full disk
	// often shows up. A conversion error comes first, if there was one.
	if closeErr := errorsFile.Close(); closeErr != nil && err == nil {
		err = fmt.Errorf("writing %s: %w", errorsPath, closeErr)
	}
	return s, err
}
$ ./csv2json survey.csv
line,reason
5,"score ""five"" is not a number"
6,score 9 is outside 1 to 5
9,wrong number of fields
{"evaluation_id":1001,"school":"Alexandria STEM","question":"Q1","score":5,"comment":"clear explanations","words":2}
{"evaluation_id":1001,"school":"Alexandria STEM","question":"Q2","score":4,"comment":null,"words":0}
{"evaluation_id":1002,"school":"Cairo Language School","question":"Q1","score":3,"comment":"too fast","words":2}
{"evaluation_id":1003,"school":"Giza Primary","question":"Q2","score":2,"comment":"needs more examples and a slower pace","words":7}
{"evaluation_id":1005,"school":"Aswan Secondary","question":"Q1","score":4,"comment":"شرح واضح جدا شكرا","words":4}
time=2026-12-03T18:40:51.007+02:00 level=INFO msg=converted rows=8 written=5 rejected=3
time=2026-12-03T18:40:51.007+02:00 level=ERROR msg="too many rejected rows: check the export before using the output" max_percent=5
exit code 1

On a terminal stdout and stderr are mixed; the order above is the order they were written in. The rejected rows come first because each writer is flushed at the end, the CSV one before the JSON one. 5 answers written out of 8 rows, and 3 rejected with their line and reason. The multi-line comment became one clean string, and the Arabic one kept its words.

3 of 8 is 37.5% rejected, above the default limit of 5%, so the run ends with exit code 1 even though every row was handled. On this deliberately bad sample that is the right answer: an export this broken should not go into the analysis unnoticed.

$ ./csv2json -errors errors.csv -max-rejected 80 survey.csv
{"evaluation_id":1001,"school":"Alexandria STEM","question":"Q1","score":5,"comment":"clear explanations","words":2}
{"evaluation_id":1001,"school":"Alexandria STEM","question":"Q2","score":4,"comment":null,"words":0}
{"evaluation_id":1002,"school":"Cairo Language School","question":"Q1","score":3,"comment":"too fast","words":2}
{"evaluation_id":1003,"school":"Giza Primary","question":"Q2","score":2,"comment":"needs more examples and a slower pace","words":7}
{"evaluation_id":1005,"school":"Aswan Secondary","question":"Q1","score":4,"comment":"شرح واضح جدا شكرا","words":4}
time=2026-12-03T18:40:51.519+02:00 level=INFO msg=converted rows=8 written=5 rejected=3

With a file for the rejected rows and a higher limit: stdout has only JSON, and stderr only the summary. ./csv2json … > answers.jsonl gives the analysis pipeline a clean file.

$ ./csv2json missing.csv
time=2026-12-03T18:40:51.979+02:00 level=ERROR msg="conversion failed" err="open missing.csv: no such file or directory"
exit code 1

A missing input: the error, logged, and exit code 1.

The benchmark: the same tool in PHP

To compare fairly, the PHP version does the same work: it streams with fgetcsv, applies the same rules in the same order with the same messages, cleans the comment with a Unicode regex and mb_strtolower, and writes json_encode per line and every rejected row with its line. On the generated files, both tools write byte-for-byte identical JSON Lines and identical rejected rows (diff prints nothing).

The test data

generate.php
<?php

// Usage: php generate.php 100000 > survey.csv
// A school-evaluation export with realistic free text and about 1 bad row in 1,000.

$rows = (int) ($argv[1] ?? 100_000);
mt_srand(42);

$schools = ['Alexandria STEM', 'Cairo Language School', 'Giza Primary', 'Luxor Prep', 'Aswan Secondary'];
$comments = [
    'Clear explanations, thank you.',
    'Too  FAST!! Needs more examples.',
    'شرح واضح جدا، شكرا',
    'The teacher was patient and the homework was useful',
    '',
    '',
];

$out = fopen('php://stdout', 'w');
fputcsv($out, ['evaluation_id', 'school', 'question', 'score', 'comment'], escape: '');
for ($i = 0; $i < $rows; $i++) {
    $score = mt_rand(1, 1000) === 1 ? 'five' : (string) mt_rand(1, 5);   // ~0.1% bad scores
    fputcsv($out, [
        intdiv($i, 10) + 1000,
        $schools[mt_rand(0, count($schools) - 1)],
        'Q' . ($i % 10 + 1),
        $score,
        $comments[mt_rand(0, count($comments) - 1)],
    ], escape: '');
}

csv2json in PHP

csv2json.php
<?php

// The same job as csv2json: php csv2json.php survey.csv errors.csv > answers.jsonl

[$_, $inputPath, $errorsPath] = $argv;

$input = fopen($inputPath, 'r') ?: exit("cannot open $inputPath\n");
$errors = fopen($errorsPath, 'w');
fputcsv($errors, ['line', 'reason'], escape: '');

$headers = array_map('trim', fgetcsv($input, escape: ''));
$headers[0] = preg_replace('/^\x{FEFF}/u', '', $headers[0]);
$line = 1;
$rows = $written = $rejected = 0;

while (($fields = fgetcsv($input, escape: '')) !== false) {
    $line++;
    $rows++;
    $row = count($fields) === count($headers) ? array_combine($headers, array_map('trim', $fields)) : null;
    $reason = match (true) {
        $row === null => 'wrong number of fields',
        !ctype_digit($row['evaluation_id']) || (int) $row['evaluation_id'] < 1 => "evaluation_id \"{$row['evaluation_id']}\" is not a positive number",
        !ctype_digit($row['score']) => "score \"{$row['score']}\" is not a number",
        (int) $row['score'] < 1 || (int) $row['score'] > 5 => "score {$row['score']} is outside 1 to 5",
        $row['school'] === '' => 'school is empty',
        !preg_match('/^Q\d+$/', $row['question']) => "question \"{$row['question']}\" is not like Q1",
        default => null,
    };
    if ($reason !== null) {
        fputcsv($errors, [$line, $reason], escape: '');
        $rejected++;
        continue;
    }

    $words = preg_split('/[^\p{L}\p{N}]+/u', mb_strtolower($row['comment']), flags: PREG_SPLIT_NO_EMPTY);
    echo json_encode([
        'evaluation_id' => (int) $row['evaluation_id'],
        'school' => $row['school'],
        'question' => $row['question'],
        'score' => (int) $row['score'],
        'comment' => $words === [] ? null : implode(' ', $words),
        'words' => count($words),
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR), "\n";
    $written++;
}

fwrite(STDERR, "csv2json.php: $rows rows, $written written, $rejected rejected\n");

Results

Measured on the machine this site is built on: 2 cores, Linux, PHP 8.3.6 CLI, Go 1.27.4 with a plain go build. Each run three times in the same sitting; the table shows the range. Memory is the peak resident memory the operating system reports for the process.

InputToolTimePeak memory
100K rows (5.4 MB)PHP 8.30.5–0.8 s31 MB
100K rows (5.4 MB)Go csv2json0.16–0.19 s13 MB
1M rows (55 MB)PHP 8.35.5–6.4 s31 MB
1M rows (55 MB)Go csv2json1.9–2.1 s13 MB

What the numbers say, honestly. Both tools stream, so both keep memory flat whatever the file size: the 600K-row crash in Sara’s message came from collect(), not from PHP itself, and LazyCollection would fix that part. Go is about 3 times faster here, on one core: this csv2json has no concurrency at all. Week 4 adds goroutines, and on a machine with more cores the gap can grow.

For a weekly 100K-row export, half a second of PHP is fine, and rewriting it in Go would be a waste. At millions of rows a day, when the same validation runs inside an HTTP request, or when the tool must run on a machine with no PHP, the difference starts to pay. That judgement, not the language, is the skill.

Calling it from Laravel

app/Jobs/ImportEvaluationExport.php
<?php

namespace App\Jobs;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Process;
use RuntimeException;

final class ImportEvaluationExport implements ShouldQueue
{
    use Queueable;

    public function __construct(private string $csvPath) {}

    public function handle(): void
    {
        $jsonl = storage_path('app/imports/answers.jsonl');
        $errors = storage_path('app/imports/rejected.csv');

        $result = Process::timeout(600)->run(sprintf(
            '%s -errors %s %s > %s',
            base_path('bin/csv2json'),
            escapeshellarg($errors),
            escapeshellarg($this->csvPath),
            escapeshellarg($jsonl),
        ));

        if ($result->failed()) {
            throw new RuntimeException("csv2json failed ({$result->exitCode()}): {$result->errorOutput()}");
        }
        // answers.jsonl is clean: stream it into the database with LazyCollection, line by line.
    }
}

The PHP side keeps the queue, the retries, the notifications and the database; Go does the one heavy loop, as a single binary in bin/ with no runtime to install. Week 4 connects the two properly: a Go worker that processes what Laravel queues, with every failure visible on the PHP side.

PracticeLearn Go with Tests: Dependency Injection; one more rule

Do Dependency Injection in Learn Go with Tests: it is the io.Writer idea of today’s convert, taken one step further.

Exercise: duplicate answers

Some schools export the same answer twice. Reject a row whose evaluation_id and question were already seen, with the reason duplicate of line N. Use a map keyed by a small struct (the generics lesson showed struct keys). Add a case to the test first. What does the map cost in memory on a 1M-row file, and is that acceptable?

Remember

  • A file you write is closed with its error checked; a file you read can be closed with defer.
  • Measure before you rewrite: the speed-up has to pay for a second language in the stack.

Tomorrow is the checkpoint: flat memory on a 1M-row file, and five broken programs from this week.