---
title: Files, CSV and JSON
description: Read and write files, and convert CSV and JSON
---
Read text with `•nget`, parse it with `•csv` or `•json`, and calculate. `•csv⁻` and `•json⁻` produce text, which `•nput` writes to a file.

```text
sales←•csv •nget "sales.csv"
totals←+/¨sales
"totals.json" •nput •json⁻ totals
```

Options go on the left as a keyed vector, and the data goes on the right. Option names are case-insensitive.

<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->

## Files

```bpl
]help •nget
```

# `•nget` — Read a file

`•nget path` reads a UTF-8 text file. `•nget "-"` reads the rest of standard input. A path that starts with `./` or `../` is relative to the file holding the code, as for [`•load`](system/load.md).

`X •nget path` takes an options record on the left: `binary` (`1` reads a vector of byte values, as in `["binary":1] •nget path`) and `encoding` (`"UTF-8"`, the only encoding). [Files](data.md#files) covers bytes and options.

Errors: `IO` for missing files, invalid UTF-8, other file errors, and standard input that fails or that the frontend doesn't provide; `DOMAIN` for invalid options.

```bpl
]help •nput
```

# `•nput` — Write a file

`path •nput data` writes `data` to a new file. It returns the number of bytes written as a [shy](terms.md#term-shy) result. Text is written as UTF-8. An array of numbers is written as bytes, each from 0 to 255, in ravel order. A path that starts with `./` or `../` is relative to the file holding the code, as for [`•load`](system/load.md).

`"-" •nput data` writes `data` to standard output, with no line ending added. Text written this way just before a read of [`⎕`](https://bpl.fast.ai//glyphs/quad.html) is that read's prompt. See [`⎕`](glyphs/quad.md#input).

`X •nput data` takes an options record on the left: `path`, `overwrite` (`1` replaces an existing file, as in `["path":p "overwrite":1] •nput data`) and `encoding` (`"UTF-8"`, for text). With the option `unique`, `•nput` writes a new file with a unique name inside the directory `path`. It returns the new file's path, which is displayed. The option `prefix` sets the start of the name, as for [`•mkdir`](system/mkdir.md). Plain text on the left is the path. [Files](data.md#files) covers bytes and options.

Errors: `IO` for an existing file without `overwrite`, and for other file errors; `DOMAIN` for invalid options or byte values, and for bytes written to standard output that aren't UTF-8.

```bpl
text←•nget "sales.csv"
"copy.csv" •nput text
["path":"copy.csv" "overwrite":1] •nput text
```

The parent directory must already exist when `•nput` writes a file. With `"binary":1`, `•nget` returns exact integers in `0…255`. `•nput` writes an array of whole numbers in `0…255` as bytes. It checks the data before opening the file.

```bpl
bytes←["binary":1] •nget "image.bin"
"copy.bin" •nput bytes
"UTF-8" •ucs bytes           ⍝ decode UTF-8 when appropriate
bytes-256ₓ×bytes≥128ₓ         ⍝ signed-byte interpretation
```

## Numeric input

```bpl
]help •vfi
```

# `•vfi` — Numeric input

`•vfi text` returns two vectors, `[valid numbers]`, with a flag and a value for each whitespace-separated field of `text`. An invalid field has the flag `0ₓ` and the value zero. The zero is converted to the other values' type, as a reader's `fill` is: `•vfi "2ₓ nope"` gives `[[1 0]ₓ;[2 0]ₓ]`. Fields are parsed as numbers, never executed.

A field can be any of BPL's written forms of a number, with plain letters or subscripts. `•vfi` reads back the numbers that [`⍕`](https://bpl.fast.ai//glyphs/thorn.html) displays:

```bpl
•vfi ⍕1r3 1j2 1e20   ⍝ [[1 1 1]ₓ [1ᵣ3 1ⱼ2 1ₑ20]]
```

`separators •vfi text` splits on each character in `separators` instead. It trims whitespace around fields. An empty field is a valid `0`. [Numeric input](data.md#numeric-input) covers it.

Errors: `DOMAIN` when either argument is not text.

Invalid fields have flag `0ₓ` and value `0`. Valid fields have flag `1ₓ`:

```bpl
[valid nums]←•vfi "12 nope -3 1.5"
valid
nums
valid#nums
```

```output
[1 0 1 1]ₓ
12 0 ¯3 1.5
12 ¯3 1.5
```

A number written plainly, such as `2` or `1.5`, is approximate. A number written with an `x` suffix, such as `3x`, or as a rational, such as `1r4`, is exact. `•vfi` also accepts the subscript forms that [`⍕`](https://bpl.fast.ai//glyphs/thorn.html) displays, such as `1ᵣ4` and `1ₑ20`, complex numbers written with `j` or `J`, [`∞`](https://bpl.fast.ai//glyphs/infinity.html), `inf`, `infinity`, ASCII signs and signed exponents. `•vfi` converts `nan` to `$n`.

If any number is approximate and every number can be represented exactly as a float, all the numbers become approximate. Otherwise each number keeps its kind. The `0` from an invalid field doesn't count as approximate.

```bpl
1⊃•vfi "2 3x 1r4 1j-2 -1e-3 ∞"
```

```output
2 3 0.25 1ⱼ¯2 ¯0.001 ∞
```

`separators •vfi text` splits `text` on any character in `separators` and trims surrounding whitespace from each field. Empty fields are valid and have value `0`. Internal whitespace remains part of the field.

```bpl
',' •vfi "3.9,2.4,,76,"
'◇' •vfi "1 ◇ 2 3 ◇ 4"
```

```output
(1ₓ 1ₓ 1ₓ 1ₓ 1ₓ◇3.9 2.4 0 76 0)
(1ₓ 0ₓ 1ₓ◇1 0 4)
```

For empty input, `•vfi` returns two empty vectors. When `separators` is `""`, nonempty `text` is one field. A DOMAIN error occurs if either argument is not character text.

## JSON

```bpl
]help •json
```

# `•json` — JSON

`•json text` reads JSON5, which includes all JSON. JSON5 adds comments, trailing commas, single-quoted strings, unquoted keys, hexadecimal numbers, `Infinity` and `NaN`. Objects become keyed vectors. Arrays become vectors. Strings become character vectors. An integer outside the 64-bit range is read as its nearest float: `9223372036854775808` becomes `9.223372037ₑ18`. `true` and `false` become `$t` and `$f`.

`•json⁻ Y` writes JSON text. Keyed axes become objects. Unkeyed axes become arrays. Character vectors become strings. Keyed entries that hold functions are left out. NaN is written as `null`.

`["fill":v] •json text` reads `null` as `v`. The fill is converted to its array's type if the conversion preserves its value: `["fill":0] •json "[1,null,3]"` gives `[1 0 3]ₓ`, and `["fill":0] •json "[true,null]"` gives `$t $f`. If the conversion would change the fill's value, as with the default NaN beside integers, the array is read as floats. `["fill":v] •json⁻ Y` writes `v` as `null`. [JSON](data.md#json) covers the conversions.

Under [static kinds](numbers.md#static-kinds), an array of integers is read at the [`int`](system/prefs.md) width, and a value that doesn't fit raises a `DOMAIN` error. `["types":R] •json text` sets the type of the arrays in named fields: `R` maps a field's name to a number of that type, as `•csv`'s `types` option does, and every array in a field of that name is read as that type:

```bpl
•prefs ["kinds":"static"]
(["types":["id":0ₓ₈]] •json "{""id"":[3000000000,7],""n"":[1,2]}").id    ⍝ [3000000000 7]ₓ₈
•prefs ["kinds":"dynamic"]
```

Errors: `DOMAIN` for malformed JSON, with its line and column, and for values that JSON can't hold: an infinity that isn't `fill`, out-of-range floats, rationals that aren't whole, complex numbers and other functions. Also `DOMAIN` for a value that can't be converted to its array's type unchanged, and for a `types` entry that names no field holding an array.

Nested structure is kept:

```bpl
person←•json "{""name"":""Ann"",""scores"":[10,20]}"
person.name
person.scores
```

```output
"Ann"
[10 20]ₓ
```

`•json` also reads JSON5, with comments, trailing commas, single-quoted strings and unquoted keys.

```bpl
•json "{name: 'Ann', scores: [10, 20,]}  // JSON5"
```

```output
["name":"Ann" "scores":[10 20]ₓ]
```

`"f.json" •nput •json⁻ Y` writes JSON to a file. `•json⁻` exports the contents of a scalar array. Axis names and empty-array [prototypes](terms.md#term-prototype) are left out:

```bpl
•json⁻ ["name":"Ann" "scores":[10 20]ₓ]
•json⁻ [1 2◇3 4]ₓ
•json⁻ •json "{}"
```

```output
"{""name"":""Ann"",""scores"":[10,20]}"
"[[1,2],[3,4]]"
"{}"
```

JSON integers are exact when they fit in 64 bits. A larger one is read as its nearest float, because only `ᵣ` makes unbounded integers. Numbers with a decimal point or an exponent are approximate. Numbers in a JSON array combine by the rule in [Numeric input](#numeric-input). `true` and `false` are read as `$t` and `$f`. `•json⁻` writes Booleans back as `true` and `false`:

```bpl
•json "[9223372036854775809,1.5,true,false]"
•json⁻ •json "[true,false]"
```

```output
9.223372037ₑ18 1.5 1 0
"[true,false]"
```

`fill` replaces `null` on import. The fill value is converted to the array's type if that conversion preserves its value, as it does for `¯1` here. Because the default `fill` is NaN, an integer array containing `null` is read as floats. On export, NaN and the `fill` value become `null`:

```bpl
•json "[1,null,3]"
["fill":¯1] •json "[1,null,3]"
["fill":∞] •json⁻ 1ₓ ∞ 3ₓ
```

```output
1 $n 3
[1 ¯1 3]ₓ
"[1,null,3]"
```

For duplicate object members, `•json` keeps the last value.

## CSV

```bpl
]help •csv
```

# `•csv` — CSV

`•csv text` parses CSV into a vector of columns. Headers become keys. Numeric columns become numbers. An integer outside the 64-bit range is read as its nearest float. Missing numeric cells become the `fill` option's value, NaN by default. Missing text cells become `""`.

`ifill` replaces missing cells in integer columns without replacing NaNs in float columns. It must be a whole real number. It applies to inferred integer columns and to integer columns requested by `types`, not to Boolean or float columns.

`fills` overrides individual columns, as a record keyed by column name or a vector with one value per column. Its values must be numeric for numeric columns and text for text columns. The precedence is `fills`, then `ifill` for integer columns, then `fill` for numeric columns or `""` for text.

A fill is converted to its column's inferred type when that type can hold its value exactly. With `ifill` set to `0`, a missing integer is read as `0ₓ`. NaN or `0.5` from `fill` or `fills` instead makes an inferred integer column floating-point. A column whose cells are all missing is text unless `types` gives it a numeric type.

Under [static kinds](numbers.md#static-kinds), every integer column is read at the `int` width whatever its values, as every new integer is. A value that doesn't fit raises a `DOMAIN` error that names the column.

The `types` option sets each column's type, given as a value of that type. A number, such as `0ₓ₈`, `0ₚ` or `$f`, makes a numeric column of its type. That type must hold each of the column's values exactly, and the fill at its missing cells, or `•csv` raises a `DOMAIN` error. With a float type, values are rounded to its width. With text, such as `""`, the column is read as written: `02134` stays `"02134"`. A record sets the columns that it names. A vector sets every column in order, and needs one value for each column. A file with no header needs a vector:

```bpl
•prefs ["kinds":"static"]
t←"id,price,flag,zip",(•ucs 10),"3000000000,1.5,1,02134",(•ucs 10),"7,2.25,0,10001"
T←["types":["id":0ₓ₈ "price":0ₚ "flag":$f "zip":""]] •csv t
T.id                       ⍝ [3000000000 7]ₓ₈
T.flag                     ⍝ $t $f
(•storage T.price).kind    ⍝ "float64"
T.zip                      ⍝ "02134" "10001"
•prefs ["kinds":"dynamic"]
["header":$f "types":["" 0ₓ]] •csv "a,12",(•ucs 10),"b,7"   ⍝ [["a" "b"] [12 7]ₓ]
```

`•csv⁻ T` writes CSV text for a vector of columns. Keys supply the header. Column lengths must agree. NaN and the selected fill for each column are written as empty cells. `fills`, `ifill` and `fill` have the same precedence as on import.

`•csv` and `•csv⁻` both take options on the left: `header`, `separator`, `quote`, `doublequote`, `escapechar`, `decimal`, `thousands`, `trim`, `fill`, `ifill` and `fills`. `•csv` also takes `missing` and `types`, and `•csv⁻` takes `forcequotes` and `eol`. `"forcequotes":2` quotes every field. [CSV](data.md#csv) describes the options.

Errors: `DOMAIN` for invalid options, duplicate headers, incompatible fills, and cells that CSV can't hold: rationals that aren't whole, complex numbers, functions or nested cells, and for a value that doesn't keep itself in its column's type; `LENGTH` for unequal record widths or columns, or a `types` or `fills` vector of the wrong length.

Each numeric column uses compact integer or float storage where possible:

```bpl
text←"price,qty
10.5,2
20.0,4"
T←•csv text
T
T.qty
+/¨T
```

```output
["price":[10.5 20] "qty":[2 4]ₓ]
[2 4]ₓ
["price":30.5 "qty":6ₓ]
```

`"f.csv" •nput •csv⁻ T` writes CSV to a file. When `T` has no keys, `•csv⁻` writes the data without a header row. Parsing the text restores the columns:

```bpl
T←["price":10.5 20;"qty":2ₓ 4ₓ]
•csv •csv⁻ T
```

```output
["price":[10.5 20] "qty":[2 4]ₓ]
```

### CSV options

```bpl
text←"price;qty
10,5;2
20,0;4"
opts←["separator":';' "decimal":',']
T←opts •csv text
T
csv←opts •csv⁻ T
opts •csv csv
```

```output
["price":[10.5 20] "qty":[2 4]ₓ]
["price":[10.5 20] "qty":[2 4]ₓ]
```

| Option | Default | Meaning |
|--- |--- |--- |
| `header` | Import: `1`; export: has keys | Read/write column names |
| `separator` | `','` | Field separator; use `•ucs 9` for TSV |
| `quote` | `'"'` | Quote character; `""` disables quoting |
| `doublequote` | `1` | Represent a quote inside a quoted field by doubling it |
| `escapechar` | `""` | Escape character inside quoted fields |
| `decimal` | `'.'` | Decimal mark: `'.'` or `','` |
| `thousands` | `""` | Group separator; groups after the first contain three digits |
| `trim` | `0` | Trim surrounding whitespace from fields |
| `fill` | Import: NaN; export: none | Numeric missing-cell replacement. On export, NaN and this exact value are written as an empty cell |
| `ifill` | none | Whole real fill for integer columns; float and Boolean columns are unchanged |
| `fills` | none | Per-column fills: a record keyed by name, or a vector in column order. Overrides `ifill` and `fill`; numeric fills for numeric columns, text fills for text |
| `missing` | [`⍬`](https://bpl.fast.ai//glyphs/zilde.html) | Additional missing-cell strings; empty cells are always missing |
| `types` | none | Import: column types, each given by a value of that type: a number for a numeric column, or text such as `""` for a text column. A record names columns, as in `["id":0ₓ₈ "zip":""]`. A vector gives every column's type in order. Under static kinds, integer columns otherwise take the `int` width |
| `forcequotes` | `0` | Export: `0` as needed, `2` all fields |
| `eol` | `•ucs 10` | Export: LF or CRLF (`•ucs 13 10`) |

```bpl
text←"id,qty
00123,5"
T←["types":["id":""]] •csv text
T.id
```

```output
["00123"]
```

`separator`, `quote` and `escapechar` must be distinct ASCII characters other than CR, LF or NUL. Fields may contain Unicode characters, doubled quotes and embedded newlines. `•csv` accepts LF, CRLF and CR record endings. When `escapechar` is set, `•csv⁻` quotes every field and doubles each literal escape character. When `quote` is `""`, `•csv⁻` gives DOMAIN for a field that requires quoting.

### Numbers and missing cells

To infer a column's type, `•csv` examines the whole column, ignoring missing cells. Integer fields produce exact numbers. Decimal and scientific notation produce floats. A column containing other text stays text. Quoted numbers are also used to infer the column's type.

```bpl
T←•csv "count,label
2,001
3,yes"
T.count
T.label
```

```output
[2 3]ₓ
"001" "yes"
```

A column of integers uses integer storage when every value fits in 64 bits. A larger integer is read as its nearest float. A value with a decimal point or an exponent is approximate. A column's numbers combine by the rule in [Numeric input](#numeric-input).

By default, missing numeric cells become NaN, written `$n`. Because NaN is a float, an integer column with a missing cell becomes floats. If that column also holds an integer too large for a float to represent exactly, each item keeps its kind in [mixed storage](terms.md#term-mixed-storage). Missing text cells become `""`. A column whose cells are all missing is read as text unless `types` gives it a numeric type.

```bpl
T←•csv "price,qty
10.5,2
,4"
T.price
T.qty
```

```output
10.5 $n
[2 4]ₓ
```

Use `missing` to add missing-cell strings and `fill` to replace missing numeric cells:

```bpl
text←"qty
NA
4"
["missing":"NA" "fill":¯1] •csv text
```

```output
["qty":[¯1 4]ₓ]
```

Use `ifill` to keep missing integer counts as integers without replacing NaNs in float columns. `fills` overrides individual columns. Here IDs use `¯1`, quantities use `0`, prices keep NaN, and labels use `"unknown"`:

```bpl
text←"id,qty,price,label
7,3,1.5,known
,,,"
opts←["ifill":0 "fills":["id":¯1 "label":"unknown"]]
T←opts •csv text
T
opts •csv⁻ T
```

```output
["id":[7 ¯1]ₓ "qty":[3 0]ₓ "price":[1.5 $n] "label":["known" "unknown"]]
"id,qty,price,label
7,3,1.5,known
,,,
"
```

`•csv⁻` writes negative numbers with [`-`](https://bpl.fast.ai//glyphs/minus.html), floats in decimal or scientific notation, and exact integers plainly. It writes infinity as `inf` or `-inf`. NaN and each column's selected fill are written as empty cells, using the same `fills`, `ifill`, `fill` precedence as on import. It gives DOMAIN for rationals that aren't whole, complex numbers, functions and nested nonstring cells.

For empty input, `•csv` returns an empty unkeyed vector. For header-only input, it returns keyed empty columns. Empty header names are allowed. Duplicate header names give DOMAIN. `•csv` gives LENGTH for unequal record widths, and `•csv⁻` gives LENGTH for unequal column lengths. When `types` gives a column a numeric type and a cell is not a number, the DOMAIN error reports the cell's row and column.

## Repeated text

When text is repeated in `•csv`, `•json` or Python data, all cells containing that text share the same array. This sharing applies to the first 65,536 distinct texts in each `•csv` column, `•json` document and Python conversion. A long column of repeated text then takes less memory, and [`=`](https://bpl.fast.ai//glyphs/equals.html), [`∪`](https://bpl.fast.ai//glyphs/down-shoe.html), [`⍷`](https://bpl.fast.ai//glyphs/epsilon-underbar.html) and [`⌸`](https://bpl.fast.ai//glyphs/quad-equal.html) compare only the distinct arrays.

For text created in BPL, such as words produced by splitting a string, each cell stores a separate array. Selecting each word from the distinct words makes cells containing the same word share an array:

```bpl
words←' ' ≠⊆⊢ "to be or not to be"
u←∪words
words←[uιwords]⌷u
words
```

```output
"to" "be" "or" "not" "to" "be"
```
