Taskintro
Convert CSV to JSON
Also called CSV to JSON, turn CSV rows into JSON objects, export a CSV file as JSON.
Convert CSV text with a header line to a JSON array with one object for each record, with the members in the order of the header and each value kept as a string.
- Evidence
- Code in 5 languages
Task
Convert CSV text to JSON text. The first record of the CSV is the header. The result is a JSON array with one object for each record after the header. Each object has one member for each name of the header, in the order of the header, and the value of the member is the field in the same column.
The input follows RFC 4180: commas separate the fields, and "Fields containing line breaks (CRLF), double quotes, and commas should be enclosed in double-quotes."1 A double quote inside a quoted field is written twice.1 The solution accepts LF as well as CRLF at the end of a record. A CRLF inside a quoted field becomes LF. An empty line gives no record.
For example, this CSV text:
name,age
Ada,36
"Lovelace, Ada",36
gives this JSON text:
[{"name":"Ada","age":"36"},{"name":"Lovelace, Ada","age":"36"}]
Each value is a JSON string, also 36. CSV has no types, so the solution does not guess them. A program that needs a number converts the field when it reads the JSON.
The JSON text has no white space outside the strings. Each string writes " and \ with a backslash before them, a tab as \t and an LF as \n. Every other character is written as itself, also <, & and characters outside ASCII. These rules make one exact text for each input, so the cases can compare the text.
The solution reports an error and returns no text in two cases: a record has more or fewer fields than the header (field-count), and a quoted field has no closing quote or has text after its closing quote (bad-quote).
Solutions
Each solution reads the CSV into a list of records, checks the number of fields, and writes the JSON array. Python's json.dumps keeps the order of a dict, so it writes the whole list. The JavaScript, C# and Go solutions write the brackets, the braces, the colons and the commas themselves, because their JSON writers change the order of the members or escape more characters (see the pitfalls).
- Python.
csv.readerreads the text from anio.StringIOwithnewline=''. Withstrict=True, it raisescsv.Erroron a bad quote, and "The default is False."2 The code checks the number of fields and skips the empty list that the reader gives for an empty line. Each record is adict, which keeps the order of insertion, sojson.dumpscan write the whole list.ensure_ascii=Falsekeeps the characters outside ASCII, andseparators=(',', ':')removes the spaces.3 - JavaScript and TypeScript (Node.js). Node.js has no CSV parser, so
parseCsvis a small state machine for RFC 4180. It is the same as the one in Read a CSV file.JSON.stringifywrites each name and each value as a string, and the code joins them. The error is aCsvErrorwith akindfield. The TypeScript file adds types only. - C#.
Parseis the same state machine. A smallWriteStringwrites each JSON string, becauseUtf8JsonWriterescapes characters that the contract writes as themselves (see the pitfalls).CsvExceptionextendsFormatExceptionand has aKind. - Go.
csv.NewReaderreads the records. "Blank lines are ignored."4 "The Reader converts all \r\n sequences in its input to plain \n, including in multiline field values".4 WithFieldsPerRecordat 0, a record with a different number of fields gives an error that wrapscsv.ErrFieldCount. Ajson.EncoderwithSetEscapeHTML(false)writes each string, and the code removes the newline thatEncodeadds. The error is a*CSVErrorwith aKind.
Java, Rust, C, C++ and Bash have no JSON writer in their standard library, so this page has no solution in those languages. The file matrix.yaml names the libraries to use.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl. Each case gives the CSV text and the JSON text that the solution must return.
simple,quoted-comma,header-onlyandno-final-newline: the common shapes. A header with no records gives[].escaped-quote: the CSV field"She said ""hi""."becomes the JSON string"She said \"hi\".".newline-in-fieldandcrlf: a line break inside a quoted field becomes\nin the JSON, also when the CSV has CRLF.backslash-and-tab:C:\tempbecomes"C:\\temp", and a tab becomes\t.numeric-text:007,02134,trueand1e3stay strings. A number would lose the leading zeros, andtruewould become a Boolean.numeric-names: the names2024,2023andnamekeep the order of the header.html-chars:a<b && c>dis written as it is, with no\u003c.empty-fields,spacesandblank-lines: an empty field becomes"", spaces stay, and empty lines give no record.empty-text: no text gives[].non-ascii:Zürich,東京and🙂are written as themselves.
The cases in cases/errors.jsonl must give an error: a record with too few fields, a record with too many, a quote with no end and text after a closing quote. The toolchain does not load this file yet, so each test file reads it itself.
Pitfalls
JSON.stringifyputs names that look like numbers first.JSON.stringifywrites the members in the order of the own keys of the object. For an ordinary object,OrdinaryOwnPropertyKeystakes each key that "is an array index, in ascending numeric index order", and only then the other strings "in ascending chronological order of property creation".5 So a header with years changes order:
This code runs but gives a wrong answer on purpose.
const header = ["2024", "2023", "name"];
const row = ["10", "9", "x"];
console.log(JSON.stringify(Object.fromEntries(header.map((name, k) => [name, row[k]]))));
{"2023":"9","2024":"10","name":"x"}
The JavaScript solution writes each member itself, in the order of the header.
- Go sorts the names of a map and escapes HTML characters. For a map, "The map keys are sorted and used as JSON object keys".6
json.Marshalalso writes<,>and&as\u003c,\u003eand\u0026, "so that the JSON will be safe to embed inside HTML tags."6
This code runs but gives a wrong answer on purpose.
package main
import (
"encoding/json"
"fmt"
)
func main() {
record := map[string]string{"name": "Ada", "age": "36", "expr": "a<b && c>d"}
b, _ := json.Marshal(record)
fmt.Println(string(b))
}
{"age":"36","expr":"a\u003cb \u0026\u0026 c\u003ed","name":"Ada"}
The text is valid JSON with the same values, but the order of the header is lost. "This replacement can be disabled when using an Encoder, by calling Encoder.SetEscapeHTML (false)."6 The Go solution does that, and it writes the members in order.
- Python escapes the characters outside ASCII by default. With
ensure_ascii=True, "the output is guaranteed to have all incoming non-ASCII and non-printable characters escaped."3 The default separators also add a space after each comma and colon:3
This code runs but gives a wrong answer on purpose.
import json
records = [{"city": "Zürich", "word": "東京"}]
print(json.dumps(records))
print(json.dumps(records, ensure_ascii=False, separators=(",", ":")))
[{"city": "Z\u00fcrich", "word": "\u6771\u4eac"}]
[{"city":"Zürich","word":"東京"}]
Both lines are valid JSON. The first one is longer, and a person cannot read the escaped text.
System.Text.Jsonescapes many characters. "By default, the serializer escapes all non-ASCII characters."7JavaScriptEncoder.UnsafeRelaxedJsonEscaping"doesn't escape HTML-sensitive characters such as <, >, &, and '."7 But it still escapes a character outside the BMP, such as an emoji, as two\uescapes:
This code runs but gives a wrong answer on purpose.
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
foreach (JavaScriptEncoder? encoder in new[] { null, JavaScriptEncoder.UnsafeRelaxedJsonEscaping })
{
using var buffer = new MemoryStream();
using (var writer = new Utf8JsonWriter(buffer, new JsonWriterOptions { Encoder = encoder }))
{
writer.WriteStartObject();
writer.WriteString("word", "a<b Zürich 🙂");
writer.WriteEndObject();
}
Console.WriteLine(Encoding.UTF8.GetString(buffer.ToArray()));
}
{"word":"a\u003Cb Z\u00FCrich \uD83D\uDE42"}
{"word":"a<b Zürich \uD83D\uDE42"}
A JSON reader gets the same string back from each line. If your program only needs valid JSON, the relaxed encoder is enough. The contract asks for one exact text, so the C# solution writes the strings itself.
- Guessing types changes the data. A converter that turns each field that looks like a number into a JSON number breaks codes such as postal codes and IDs:
This code runs but gives a wrong answer on purpose.
import json
record = {"id": "007", "zip": "02134", "price": "1e3"}
guessed = {k: float(v) if k == "price" else int(v) for k, v in record.items()}
print(json.dumps(guessed))
{"id": 7, "zip": 2134, "price": 1000.0}
Keep each field as a string, or convert only the columns that you know, with Parse an integer and a check of the result.
-
Two columns with the same name give a bad object. RFC 8259 says: "The names within an object SHOULD be unique."8 For an object with a name twice, "Many implementations report the last name/value pair only."8 A Python
dictor a JavaScript object keeps only the last value too, so a column is lost with no error. The contract says that the names of the header are distinct. If your input can break this rule, check the header before the conversion. -
A CSV reader that is not strict accepts bad quotes. Python's
csv.readerreads"x"yas the fieldxyunlessstrict=True, as Read a CSV file shows.2 The converter then writes JSON from a broken file and reports nothing.
Related tasks
- Read a CSV file: read a CSV file into records.
- Write a CSV file: write records to a CSV file.
- Read and write JSON: read a JSON text and write a value back.
- CSV and JSON: the two formats.
- Parse an integer: convert a field to a number.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/convert-csv-to-json/.
"""Converts CSV text with a header line to a JSON array of objects."""
import csv
import io
import json
class CsvError(ValueError):
"""The text is not valid CSV. kind is "field-count" or "bad-quote"."""
def __init__(self, kind: str, message: str) -> None:
super().__init__(message)
self.kind = kind
def csv_to_json(text: str) -> str:
"""Returns a JSON array with one object for each record after the header."""
# newline="" gives the line breaks inside quoted fields to the csv module unchanged.
# strict=True raises csv.Error on a bad quote. The default accepts it.
reader = csv.reader(io.StringIO(text, newline=""), strict=True)
header = None
records = []
try:
for row in reader:
if not row:
continue # an empty line
if header is None:
header = row
continue
if len(row) != len(header):
raise CsvError("field-count", f"line {reader.line_num}: {len(row)} fields, want {len(header)}")
# A dict keeps the order of insertion, so the members keep the order of the header.
records.append({name: field.replace("\r\n", "\n") for name, field in zip(header, row)})
except csv.Error as e:
raise CsvError("bad-quote", str(e)) from e
# ensure_ascii=False writes non-ASCII characters as themselves.
# The separators remove the spaces after "," and ":".
return json.dumps(records, ensure_ascii=False, separators=(",", ":"))
test_csv_to_json.py 33 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/convert-csv-to-json/.
import json
import pathlib
import pytest
from csv_to_json import CsvError, csv_to_json
CASES = pathlib.Path(__file__).resolve().parents[2] / "cases"
def load(name):
with open(CASES / name, encoding="utf-8") as f:
return [json.loads(line) for line in f if line.strip()]
@pytest.mark.parametrize("case", load("basic.jsonl") + load("edge.jsonl"), ids=lambda c: c["name"])
def test_cases(case):
assert csv_to_json(case["args"]["text"]) == case["expect"]
@pytest.mark.parametrize("case", load("errors.jsonl"), ids=lambda c: c["name"])
def test_errors(case):
with pytest.raises(CsvError) as e:
csv_to_json(case["args"]["text"])
assert e.value.kind == case["error"]
def test_output_is_json():
text = 'id,note\n1,"She said ""hi""\nand left"\n'
assert json.loads(csv_to_json(text)) == [{"id": "1", "note": 'She said "hi"\nand left'}]
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/convert-csv-to-json/.
using System.Text;
/// <summary>The error for a text that is not valid CSV. Kind is "field-count" or "bad-quote".</summary>
public sealed class CsvException(string kind, string message) : FormatException(message)
{
public string Kind { get; } = kind;
}
/// <summary>Converts CSV text of RFC 4180 with a header line to a JSON array of objects.</summary>
public static class CsvToJson
{
/// <summary>Returns a JSON array with one object for each record after the header.</summary>
/// <exception cref="CsvException">a bad quote, or a record with the wrong number of fields.</exception>
public static string Convert(string text)
{
List<List<string>> rows = Parse(text);
var output = new StringBuilder("[");
for (int n = 1; n < rows.Count; n++)
{
List<string> row = rows[n];
if (row.Count != rows[0].Count)
{
throw new CsvException("field-count", $"record {n} has {row.Count} fields, want {rows[0].Count}");
}
output.Append(n > 1 ? ",{" : "{");
for (int k = 0; k < row.Count; k++)
{
if (k > 0)
{
output.Append(',');
}
WriteString(rows[0][k], output);
output.Append(':');
WriteString(row[k], output);
}
output.Append('}');
}
return output.Append(']').ToString();
}
/// <summary>Writes s as a JSON string.</summary>
/// <remarks>Utf8JsonWriter escapes each character outside the BMP, also with
/// JavaScriptEncoder.UnsafeRelaxedJsonEscaping, so the code writes the string itself.</remarks>
private static void WriteString(string s, StringBuilder output)
{
output.Append('"');
foreach (char c in s)
{
switch (c)
{
case '"': output.Append("\\\""); break;
case '\\': output.Append("\\\\"); break;
case '\b': output.Append("\\b"); break;
case '\f': output.Append("\\f"); break;
case '\n': output.Append("\\n"); break;
case '\r': output.Append("\\r"); break;
case '\t': output.Append("\\t"); break;
case < ' ': output.Append($"\\u{(int)c:x4}"); break;
default: output.Append(c); break;
}
}
output.Append('"');
}
/// <summary>Returns the length of the line break at i: 1 for LF, 2 for CRLF, 0 for none.</summary>
private static int LineBreak(string text, int i)
{
if (i < text.Length && text[i] == '\n')
{
return 1;
}
return i + 1 < text.Length && text[i] == '\r' && text[i + 1] == '\n' ? 2 : 0;
}
/// <summary>Splits RFC 4180 text into records of fields. An empty line gives no record.</summary>
public static List<List<string>> Parse(string text)
{
var records = new List<List<string>>();
int i = 0;
while (i < text.Length)
{
int empty = LineBreak(text, i);
if (empty > 0)
{
i += empty;
continue;
}
var record = new List<string>();
while (true)
{
var field = new StringBuilder();
if (i < text.Length && text[i] == '"')
{
i++;
while (true)
{
if (i >= text.Length)
{
throw new CsvException("bad-quote", "a quoted field has no closing quote");
}
if (text[i] == '"')
{
if (i + 1 >= text.Length || text[i + 1] != '"')
{
break;
}
field.Append('"');
i += 2;
}
else if (LineBreak(text, i) == 2)
{
field.Append('\n'); // CRLF inside quotes becomes LF.
i += 2;
}
else
{
field.Append(text[i++]);
}
}
i++; // the closing quote
if (i < text.Length && text[i] != ',' && LineBreak(text, i) == 0)
{
throw new CsvException("bad-quote", "text after the closing quote of a field");
}
}
else
{
while (i < text.Length && text[i] != ',' && LineBreak(text, i) == 0)
{
field.Append(text[i++]);
}
}
record.Add(field.ToString());
if (i >= text.Length || text[i] != ',')
{
break;
}
i++;
}
i += LineBreak(text, i);
records.Add(record);
}
return records;
}
}
CsvToJsonTests.cs 64 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/convert-csv-to-json/.
using System.Runtime.CompilerServices;
using System.Text.Json;
using Xunit;
public sealed class CsvToJsonTests
{
private static string CasesDir([CallerFilePath] string file = "") =>
Path.Combine(Path.GetDirectoryName(file)!, "..", "..", "cases");
private static IEnumerable<JsonElement> Load(string name) =>
File.ReadLines(Path.Combine(CasesDir(), name))
.Where(line => line.Trim().Length > 0)
.Select(line => JsonDocument.Parse(line).RootElement);
public static TheoryData<string, string, string> Cases()
{
var data = new TheoryData<string, string, string>();
foreach (JsonElement c in Load("basic.jsonl").Concat(Load("edge.jsonl")))
{
data.Add(c.GetProperty("name").GetString()!, c.GetProperty("args").GetProperty("text").GetString()!,
c.GetProperty("expect").GetString()!);
}
return data;
}
public static TheoryData<string, string, string> Errors()
{
var data = new TheoryData<string, string, string>();
foreach (JsonElement c in Load("errors.jsonl"))
{
data.Add(c.GetProperty("name").GetString()!, c.GetProperty("args").GetProperty("text").GetString()!,
c.GetProperty("error").GetString()!);
}
return data;
}
[Theory]
[MemberData(nameof(Cases))]
public void Converts(string name, string text, string expect)
{
Assert.False(string.IsNullOrEmpty(name));
Assert.Equal(expect, CsvToJson.Convert(text));
}
[Theory]
[MemberData(nameof(Errors))]
public void Rejects(string name, string text, string kind)
{
Assert.False(string.IsNullOrEmpty(name));
var e = Assert.Throws<CsvException>(() => CsvToJson.Convert(text));
Assert.Equal(kind, e.Kind);
}
[Fact]
public void OutputIsJson()
{
string json = CsvToJson.Convert("id,note\n1,\"She said \"\"hi\"\"\nand left\"\n");
JsonElement record = JsonDocument.Parse(json).RootElement[0];
Assert.Equal("She said \"hi\"\nand left", record.GetProperty("note").GetString());
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/convert-csv-to-json/.
// Converts CSV text with a header line to a JSON array of objects.
// Node.js has no CSV parser, so this file has a small one for RFC 4180.
/** The error for a text that is not valid CSV. kind is "field-count" or "bad-quote". */
export class CsvError extends Error {
constructor(kind, message) {
super(message);
this.name = "CsvError";
this.kind = kind;
}
}
/** Returns the length of the line break at i: 1 for LF, 2 for CRLF, 0 for none. */
function lineBreak(text, i) {
if (text[i] === "\n") return 1;
if (text[i] === "\r" && text[i + 1] === "\n") return 2;
return 0;
}
/** Splits RFC 4180 text into records of fields. An empty line gives no record. */
export function parseCsv(text) {
const records = [];
let i = 0;
while (i < text.length) {
const empty = lineBreak(text, i);
if (empty > 0) {
i += empty;
continue;
}
const record = [];
for (;;) {
let field = "";
if (text[i] === '"') {
i++;
for (;;) {
if (i >= text.length) throw new CsvError("bad-quote", "a quoted field has no closing quote");
if (text[i] === '"') {
if (text[i + 1] !== '"') break;
field += '"';
i += 2;
} else if (lineBreak(text, i) === 2) {
field += "\n"; // CRLF inside quotes becomes LF.
i += 2;
} else {
field += text[i++];
}
}
i++; // the closing quote
if (i < text.length && text[i] !== "," && lineBreak(text, i) === 0) {
throw new CsvError("bad-quote", "text after the closing quote of a field");
}
} else {
const start = i;
while (i < text.length && text[i] !== "," && lineBreak(text, i) === 0) i++;
field = text.slice(start, i);
}
record.push(field);
if (text[i] !== ",") break;
i++;
}
i += lineBreak(text, i);
records.push(record);
}
return records;
}
/** Returns a JSON array with one object for each record after the header. */
export function csvToJson(text) {
const [header, ...rows] = parseCsv(text);
if (header === undefined) return "[]";
const objects = rows.map((row, n) => {
if (row.length !== header.length) {
throw new CsvError("field-count", `record ${n + 1} has ${row.length} fields, want ${header.length}`);
}
// JSON.stringify of an object puts a name such as "2024" before the other names.
// So the code writes each member itself, in the order of the header.
const members = header.map((name, k) => `${JSON.stringify(name)}:${JSON.stringify(row[k])}`);
return `{${members.join(",")}}`;
});
return `[${objects.join(",")}]`;
}
csvToJson.test.js 31 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/convert-csv-to-json/.
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { test } from "node:test";
import { CsvError, csvToJson } from "./csvToJson.js";
const load = (name) =>
readFileSync(new URL(`../../cases/${name}`, import.meta.url), "utf8")
.split("\n")
.filter((line) => line.trim() !== "")
.map((line) => JSON.parse(line));
for (const c of [...load("basic.jsonl"), ...load("edge.jsonl")]) {
test(c.name, () => {
assert.equal(csvToJson(c.args.text), c.expect);
});
}
for (const c of load("errors.jsonl")) {
test(c.name, () => {
assert.throws(() => csvToJson(c.args.text), (e) => e instanceof CsvError && e.kind === c.error);
});
}
test("the output is JSON", () => {
const text = 'id,note\n1,"She said ""hi""\nand left"\n';
assert.deepEqual(JSON.parse(csvToJson(text)), [{ id: "1", note: 'She said "hi"\nand left' }]);
});
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/convert-csv-to-json/.
// Converts CSV text with a header line to a JSON array of objects.
// Node.js has no CSV parser, so this file has a small one for RFC 4180.
/** The error for a text that is not valid CSV. kind is "field-count" or "bad-quote". */
export class CsvError extends Error {
readonly kind: "field-count" | "bad-quote";
constructor(kind: "field-count" | "bad-quote", message: string) {
super(message);
this.name = "CsvError";
this.kind = kind;
}
}
/** Returns the length of the line break at i: 1 for LF, 2 for CRLF, 0 for none. */
function lineBreak(text: string, i: number): number {
if (text[i] === "\n") return 1;
if (text[i] === "\r" && text[i + 1] === "\n") return 2;
return 0;
}
/** Splits RFC 4180 text into records of fields. An empty line gives no record. */
export function parseCsv(text: string): string[][] {
const records: string[][] = [];
let i = 0;
while (i < text.length) {
const empty = lineBreak(text, i);
if (empty > 0) {
i += empty;
continue;
}
const record: string[] = [];
for (;;) {
let field = "";
if (text[i] === '"') {
i++;
for (;;) {
if (i >= text.length) throw new CsvError("bad-quote", "a quoted field has no closing quote");
if (text[i] === '"') {
if (text[i + 1] !== '"') break;
field += '"';
i += 2;
} else if (lineBreak(text, i) === 2) {
field += "\n"; // CRLF inside quotes becomes LF.
i += 2;
} else {
field += text[i++];
}
}
i++; // the closing quote
if (i < text.length && text[i] !== "," && lineBreak(text, i) === 0) {
throw new CsvError("bad-quote", "text after the closing quote of a field");
}
} else {
const start = i;
while (i < text.length && text[i] !== "," && lineBreak(text, i) === 0) i++;
field = text.slice(start, i);
}
record.push(field);
if (text[i] !== ",") break;
i++;
}
i += lineBreak(text, i);
records.push(record);
}
return records;
}
/** Returns a JSON array with one object for each record after the header. */
export function csvToJson(text: string): string {
const [header, ...rows] = parseCsv(text);
if (header === undefined) return "[]";
const objects = rows.map((row, n) => {
if (row.length !== header.length) {
throw new CsvError("field-count", `record ${n + 1} has ${row.length} fields, want ${header.length}`);
}
// JSON.stringify of an object puts a name such as "2024" before the other names.
// So the code writes each member itself, in the order of the header.
const members = header.map((name, k) => `${JSON.stringify(name)}:${JSON.stringify(row[k])}`);
return `{${members.join(",")}}`;
});
return `[${objects.join(",")}]`;
}
csvToJson.test.ts 31 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/convert-csv-to-json/.
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { test } from "node:test";
import { CsvError, csvToJson } from "./csvToJson.ts";
const load = (name: string): { name: string; args: { text: string }; expect?: string; error?: string }[] =>
readFileSync(new URL(`../../cases/${name}`, import.meta.url), "utf8")
.split("\n")
.filter((line) => line.trim() !== "")
.map((line) => JSON.parse(line));
for (const c of [...load("basic.jsonl"), ...load("edge.jsonl")]) {
test(c.name, () => {
assert.equal(csvToJson(c.args.text), c.expect);
});
}
for (const c of load("errors.jsonl")) {
test(c.name, () => {
assert.throws(() => csvToJson(c.args.text), (e: unknown) => e instanceof CsvError && e.kind === c.error);
});
}
test("the output is JSON", () => {
const text = 'id,note\n1,"She said ""hi""\nand left"\n';
assert.deepEqual(JSON.parse(csvToJson(text)), [{ id: "1", note: 'She said "hi"\nand left' }]);
});
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/convert-csv-to-json/.
// Package csvtojson converts CSV text with a header line to a JSON array of objects.
package csvtojson
import (
"bytes"
"encoding/csv"
"encoding/json"
"errors"
"strings"
)
// CSVError reports a text that is not valid CSV. Kind is "field-count" or "bad-quote".
type CSVError struct {
Kind string
Err error
}
func (e *CSVError) Error() string { return e.Kind + ": " + e.Err.Error() }
func (e *CSVError) Unwrap() error { return e.Err }
// CSVToJSON returns a JSON array with one object for each record after the header.
func CSVToJSON(text string) (string, error) {
// The reader skips empty lines, changes CRLF to LF, also inside quoted fields,
// and with FieldsPerRecord at 0 it wants the number of fields of the header in each record.
records, err := csv.NewReader(strings.NewReader(text)).ReadAll()
if errors.Is(err, csv.ErrFieldCount) {
return "", &CSVError{"field-count", err}
}
if err != nil {
return "", &CSVError{"bad-quote", err}
}
var out bytes.Buffer
// json.Marshal of a map sorts the names, so the code writes each object itself.
// SetEscapeHTML(false) writes <, > and & as themselves.
enc := json.NewEncoder(&out)
enc.SetEscapeHTML(false)
out.WriteByte('[')
for n, record := range records {
if n == 0 {
continue // the header
}
if n > 1 {
out.WriteByte(',')
}
out.WriteByte('{')
for i, field := range record {
if i > 0 {
out.WriteByte(',')
}
writeString(enc, &out, records[0][i])
out.WriteByte(':')
writeString(enc, &out, field)
}
out.WriteByte('}')
}
out.WriteByte(']')
return out.String(), nil
}
// writeString writes s as a JSON string. Encode adds a newline, and the code removes it.
func writeString(enc *json.Encoder, out *bytes.Buffer, s string) {
_ = enc.Encode(s) // Encode cannot fail for a string on a bytes.Buffer.
out.Truncate(out.Len() - 1)
}
csv_to_json_test.go 83 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/convert-csv-to-json/.
package csvtojson
import (
"bufio"
"encoding/json"
"errors"
"os"
"path/filepath"
"reflect"
"testing"
)
type testCase struct {
Name string `json:"name"`
Args struct {
Text string `json:"text"`
} `json:"args"`
Expect string `json:"expect"`
Error string `json:"error"`
}
func load(t *testing.T, name string) []testCase {
t.Helper()
f, err := os.Open(filepath.Join("..", "..", "cases", name))
if err != nil {
t.Fatal(err)
}
defer f.Close()
var cases []testCase
s := bufio.NewScanner(f)
for s.Scan() {
if len(s.Bytes()) == 0 {
continue
}
var c testCase
if err := json.Unmarshal(s.Bytes(), &c); err != nil {
t.Fatal(err)
}
cases = append(cases, c)
}
return cases
}
func TestCases(t *testing.T) {
for _, c := range append(load(t, "basic.jsonl"), load(t, "edge.jsonl")...) {
t.Run(c.Name, func(t *testing.T) {
got, err := CSVToJSON(c.Args.Text)
if err != nil || got != c.Expect {
t.Fatalf("got %q, %v; want %q", got, err, c.Expect)
}
})
}
}
func TestErrors(t *testing.T) {
for _, c := range load(t, "errors.jsonl") {
t.Run(c.Name, func(t *testing.T) {
_, err := CSVToJSON(c.Args.Text)
var e *CSVError
if !errors.As(err, &e) || e.Kind != c.Error {
t.Fatalf("got %v, want a %s error", err, c.Error)
}
})
}
}
func TestOutputIsJSON(t *testing.T) {
got, err := CSVToJSON("id,note\n1,\"She said \"\"hi\"\"\nand left\"\n")
if err != nil {
t.Fatal(err)
}
var v []map[string]string
if err := json.Unmarshal([]byte(got), &v); err != nil {
t.Fatal(err)
}
want := []map[string]string{{"id": "1", "note": "She said \"hi\"\nand left"}}
if !reflect.DeepEqual(v, want) {
t.Fatalf("got %v, want %v", v, want)
}
}
References
- Y. Shafranovich, RFC 4180: Common Format and MIME Type for Comma-Separated Values (CSV) Files, October 2005, 2 Definition of the CSV Format
- The Python Standard Library, csv, csv.reader; Dialect.strict
- The Python Standard Library, json, json.dump (ensure_ascii, separators)
- Go standard library, package encoding/csv, Overview; type Reader
- ECMA-262, ECMAScript 2026 Language Specification, 10.1.11.1 OrdinaryOwnPropertyKeys
- Go standard library, package encoding/json, Marshal; HTMLEscape; Encoder.SetEscapeHTML
- .NET documentation, How to customize character encoding with System.Text.Json, the introduction; Serialize all characters
- T. Bray (Ed.), RFC 8259: The JavaScript Object Notation (JSON) Data Interchange Format, December 2017, 4 Objects
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag 6XH89E Edit this page History Report an error Markdown