# JSON5 in SQLite: Functions, Flags and Limits | JSON5.dev


Source: https://json5.dev/tools/sqlite/

---

# JSON5 in SQLite: Functions and Limits

SQLite has read JSON5 since version 3.42.0, and it only ever writes plain JSON.

Every JSON function accepts comments, unquoted keys, single quotes and trailing commas, and the output is always strict. This page lists which calls accept JSON5, the `json_valid` flag bits, the documented deviations such as `Inf` and `QNaN`, and a tested table that stores config text.

Every result shown comes from SQLite 3.50.4, run through the `sqlite3` shell and Python, so you can see what each call returns. You will also find how to index fields with generated columns and the pitfalls that catch people out.

[Functions](#functions) [json\_valid](#valid) [Pitfalls](#pitfalls)

![A JSON5 text value entering a SQLite database table and leaving as strict JSON, with a json\_valid flag checker beside it](https://json5.dev/img/hero/tools-sqlite.png)

**TL;DR:** JSON5 input works in SQLite 3.42.0 (May 16, 2023) and later. `json(X)` turns it into canonical JSON, and `json_valid(X, 2)` tests for it. The one-argument `json_valid(X)` still answers 0 for JSON5, so existing checks keep their old meaning. Keep the original text in a column if you want to keep the comments, because nothing SQLite returns contains them.

[Which Functions](#functions) [Canonical Output](#output) [json\_valid Flags](#valid) [Deviations](#deviations) [Storing Config](#storing) [Indexing](#indexing) [Python](#python) [Pitfalls](#pitfalls) [FAQ](#faq)

![SQLite logo](https://json5.dev/images/tech/sqlite.png)

## Which Functions Accept JSON5

The SQLite JSON documentation puts it in one sentence: the JSON routines "understand all rfc-8259 JSON syntax and also JSON5 extensions", and the ability was added in version 3.42.0, released on 2023-05-16. The release log for 3.42.0 lists it as "Enhance the JSON SQL functions to support JSON5 extensions." The same release lowered the maximum nesting depth for JSON arrays and objects from 2000 to 1000.

There is no separate JSON5 switch and no extra function. Wherever a JSON function takes a JSON argument, that argument may be JSON5 text. We ran each of these against 3.50.4 with JSON5 input, and every one parsed it:

Function

Test input

Result

`json(X)`

`{ name: 'app', ports: [8080, 0x1F, +5, .5, 5.,], }`

`{"name":"app","ports":[8080,31,5,0.5,5.0]}`

`json_extract(X, path)`

`{a:{b:[1,2,3,]}}` at `$.a.b[1]`

`2`

`X -> path`

`{a:1}`

`1`

`X ->> path`

`{a:'hi'}`

`hi`

`json_type(X, path)`

`{a:NaN}`

`null`

`json_array_length(X)`

`[1,2,]`

`2`

`json_set(X, path, v)`

`{a:1,}` with `$.b` = 2

`{"a":1,"b":2}`

`json_remove(X, path)`

`{a:1,b:2}` minus `$.a`

`{"b":2}`

`json_patch(X, patch)`

`{a:1}` patched with `{b:2}`

`{"a":1,"b":2}`

`json_each(X)`

`{a:1, 'b':[2], /*c*/ c:null}`

Three rows: `a` integer, `b` array, `c` null

`json_tree(X)`

`{a:[1,{b:2}]}`

5 nodes

`jsonb(X)`

`{x:1}`

A JSONB blob (3.45.0 and later; see flags below)

SQLite itself explains why this holds across the board: most JSON functions convert text to its internal JSONB form before working, so the JSON5 parsing happens once at the front door. `json_error_position(X)`, also new in 3.42.0, returns 0 for well-formed input and otherwise the 1-based character position of the first error.

![Convert icon](https://json5.dev/images/icons/convert.png)

## Output Is Always Canonical JSON

The documentation is explicit that JSON text generated by the routines "always strictly conforms to the canonical JSON definition and does not contain any JSON5 or other extensions." That makes `json(X)` a converter you already have installed:

`SELECT json('{ // c name: ''app'', /* b */ ports: [8080, 0x1F, +5, .5, 5.,], }'); {"name":"app","ports":[8080,31,5,0.5,5.0]}`

Read the result carefully. Both comments are gone, the keys are quoted, the hex literal became `31`, the plus sign was dropped, `.5` became `0.5`, and `5.` became `5.0`, not `5`. The whole value is also minified. If the number type matters downstream, remember that `5.` is a real, not an integer. For a command-line conversion with a different tool, see the [conversion guide](https://json5.dev/tools/conversion/).

Nothing in the other direction exists: SQLite has no function that emits JSON5, and it does not preserve comments, quote style or number format on the way through. Treat JSON5 as an input convenience.

![Checklist icon](https://json5.dev/images/icons/checklist.png)

## json\_valid Flags

`json_valid(X, Y)` takes a bitmask. These are the bit values in the current documentation:

Bit

Meaning

`0x01` (1)

Text that strictly complies with canonical RFC 8259 JSON

`0x02` (2)

Text that is JSON with the JSON5 extensions

`0x04` (4)

A BLOB that superficially looks like JSONB (outer wrapper only; fast)

`0x08` (8)

A BLOB that strictly conforms to the JSONB format (slow; linear in size)

Add the bits to combine tests. The documentation singles out `6` (text with JSON5 extensions, or JSONB) as "probably the value you want". A `Y` below 1 or above 15 raises an error (so does a NULL `Y`), and a NULL `X` returns NULL. The two BLOB bits only matter on SQLite 3.45.0 (2024-01-15) and later, the release that added JSONB. Our run:

`SELECT json_valid('{x:35}') AS flag_default, -- 0 json_valid('{x:35}', 1) AS f1, -- 0 json_valid('{x:35}', 2) AS f2, -- 1 json_valid('{"x":35}', 2) AS strict_json_f2, -- 1 json_valid('{x:35', 2) AS broken, -- 0 json_valid('{x:35}', 6) AS f6; -- 1 SELECT json_valid(jsonb('{x:1}'), 2) AS blob_f2, -- 0 json_valid(jsonb('{x:1}'), 4) AS blob_f4, -- 1 json_valid(jsonb('{x:1}'), 8) AS blob_f8, -- 1 json_valid(jsonb('{x:1}'), 6) AS blob_f6; -- 1`

**One argument means flag 1.** For backward compatibility, `json_valid(X)` with no flags returns true only for strict JSON. A `CHECK (json_valid(col))` constraint therefore rejects JSON5 even on SQLite 3.42.0 and later. Use `json_valid(col, 2)`, or `6` if the column might hold JSONB. Note the last row above: a JSONB blob fails test 2, because bit 2 is for text.

![Specification icon](https://json5.dev/images/icons/spec.png)

## Documented Deviations From the Spec

SQLite says it understands "almost all of JSON5, plus a little more", and names two extensions and one restriction. Here they are with what we measured, against the [JSON5 specification](https://json5.dev/spec/):

Topic

The specification

SQLite

Measured on 3.50.4

Unquoted keys

Must be ECMAScript 5.1 IdentifierNames

Allows any Unicode character above U+007F that is not whitespace (extension, to avoid large Unicode tables)

`{é:1}` accepted and written as `{"é":1}`; `{1a:1}` and `{a-b:1}` rejected

Infinity

`Infinity`, `-Infinity`, `+Infinity`, exact case

Also `Inf`, in any mix of upper and lower case (extension)

`[Inf,-Inf,+Infinity,iNf,-INFINITY]` becomes `[9e999,-9e999,9e999,9e999,-9e999]`

NaN

`NaN`, which may carry a sign

Also `QNaN` and `SNaN` in any case, and all of them are read as `null` (extension)

`[NaN,QNaN,SNaN,nan]` becomes `[null,null,null,null]`; `json_type('NaN')` is `null`

Signed NaN

The grammar allows `+NaN` and `-NaN`

`+NaN` and `-NaN` are refused on purpose (restriction)

`json_valid('[+NaN]', 2)` and `json_valid('[-NaN]', 2)` both return 0

Two of these change data, not just syntax. Infinity does not stay infinite in the text: the canonical output writes `9e999`, a number too large for a double, which every reader then turns into infinity. NaN becomes `null`, so the information that it was a number is lost. The documentation says SQLite accepts the extra spellings because there is "a lot of JSON in the wild" with them. Parsers that follow the specification strictly will reject `Inf` and `QNaN`, so do not use SQLite's looser acceptance to validate files destined for other tools. Use a strict checker such as the [online validator](https://json5.dev/tools/online-validator/) for that.

![Database icon](https://json5.dev/images/icons/database.png)

## Storing JSON5 Config in a Table

The useful design keeps the text a person wrote, rejects bad text on insert, and exposes the fields you query. This table does all three, and we ran it on SQLite 3.50.4:

`CREATE TABLE app_config ( id INTEGER PRIMARY KEY, name TEXT NOT NULL UNIQUE, source TEXT NOT NULL CHECK (json_valid(source, 2)), doc TEXT AS (json(source)) STORED, port INTEGER AS (source ->> '$.server.port') VIRTUAL, env TEXT AS (source ->> '$.env') VIRTUAL ); INSERT INTO app_config(name, source) VALUES ('web', '{ // production web tier env: ''prod'', server: { port: 8080, host: ''0.0.0.0'', }, features: [''a'', ''b'',], }'), ('worker', '{ env: ''staging'', server: { port: 9090 } /* no host */ }'); SELECT name, port, env, doc FROM app_config;`

name

port

env

doc

web

8080

prod

`{"env":"prod","server":{"port":8080,"host":"0.0.0.0"},"features":["a","b"]}`

worker

9090

staging

`{"env":"staging","server":{"port":9090}}`

The `source` column keeps the original text; for the `web` row it is 117 characters and still contains the comment, while the canonical `doc` column is 75 characters and does not. The `CHECK` uses flag 2. The two virtual columns pull fields out with `->>` on every read, and `doc` is stored so that other tools can read strict JSON from the same row.

Bad text is refused. Inserting `{ env: prod }`, where the value is an unquoted word, failed in our run with the error `malformed JSON`. That message came from the stored `json(source)` column, not from the `CHECK` text. Either way the row is not written. For a config file you load once at startup, see how the same idea looks in plain code in the [Python guide](https://json5.dev/python/) and the [JavaScript guide](https://json5.dev/javascript/).

![Speed icon](https://json5.dev/images/icons/speed.png)

## Indexing and Generated Columns

SQLite's documentation gives the rules that matter here. Generated columns arrived in 3.31.0 (2020-01-22) and may use only scalar deterministic functions. All the JSON functions carry the deterministic flag, so a generated column such as `source ->> '$.env'` is allowed, as the table above shows. A `VIRTUAL` column is computed when read, a `STORED` one when the row is written. An index on a `STORED` column is an ordinary index; an index on a `VIRTUAL` column is an expression index (expression indexes date from 3.9.0, 2015-10-14).

The practical test is the query plan. With `CREATE INDEX app_config_env ON app_config(env)` in place, we asked for the plan of two equivalent queries:

``EXPLAIN QUERY PLAN SELECT name FROM app_config WHERE env = 'prod'; `--SEARCH app_config USING INDEX app_config_env (env=?) EXPLAIN QUERY PLAN SELECT name FROM app_config WHERE source ->> '$.env' = 'prod'; `--SCAN app_config``

The first query uses the index. The second, which spells the same expression inline, scans the table in our run. The lesson is to query the generated column by name. The documentation adds that the planner matches an indexed expression only when it is written exactly as in `CREATE INDEX`: "The query planner does not do algebra".

Two limits from the generated-columns page: you cannot `ALTER TABLE ADD COLUMN` a `STORED` column, only a `VIRTUAL` one, and a database file that contains generated columns cannot be opened by SQLite older than 3.31.0.

![Python logo](https://json5.dev/images/tech/python.png)

## From Python's sqlite3 Module

Python's `sqlite3` module uses whatever SQLite library your Python was built with, so the first thing to print is its version. If it is older than 3.42.0 the JSON5 examples fail with `malformed JSON`. Our run used Python 3.14.4 with library 3.50.4:

`import sqlite3, sys print("python", sys.version.split()[0], "sqlite", sqlite3.sqlite_version) db = sqlite3.connect(":memory:") db.execute("CREATE TABLE cfg(name TEXT PRIMARY KEY, source TEXT NOT NULL CHECK (json_valid(source, 2))") text = """{ // retry policy retries: 3, hosts: ['a.example', 'b.example',], }""" db.execute("INSERT INTO cfg VALUES (?, ?)", ("svc", text)) print(db.execute("SELECT json(source), source ->> '$.retries', json_extract(source, '$.hosts[1]') FROM cfg").fetchone()) try: db.execute("INSERT INTO cfg VALUES ('bad', '{ a: }')") except sqlite3.IntegrityError as e: print("IntegrityError:", e)`

The output, as printed:

`python 3.14.4 sqlite 3.50.4 ('{"retries":3,"hosts":["a.example","b.example"]}', 3, 'b.example') IntegrityError: CHECK constraint failed: json_valid(source, 2)`

Here the table has no generated column, so the `CHECK` reports. Two more results from the same run. `json_error_position('{a:}')` returned 4, the position of the closing brace. And a JSON5 infinity extracted with `json_extract` came back from SQLite as the SQL type `real` with the value `inf`, which Python received as `float('inf')`; `0x10` extracted as the integer 16, and a `NaN` extracted as `None`. If you want to do the JSON5 parsing in Python instead, the [Python guide](https://json5.dev/python/) compares the libraries.

![Warning icon](https://json5.dev/images/icons/warning.png)

## Pitfalls

### 1\. Quoting a value is not parsing it

A JSON5 string passed to `json_array` or `json_quote` is treated as text, not as JSON. Wrap it in `json()` to embed it as structure:

`json_quote('{a:1}') -- "{a:1}" json_array('{a:1}') -- ["{a:1}"] json_array(json('{a:1}')) -- [{"a":1}]`

### 2\. Old SQLite fails on JSON5

Before 3.42.0 the same SQL raises `malformed JSON`. A desktop app that uses the operating system's SQLite, or a language runtime with an old bundled library, can differ from your laptop. Print `sqlite_version()` in a test.

### 3\. Reparsing on every call

A `TEXT` column holding JSON5 is parsed again by every `json_extract`, because the documentation says text input is translated before use. For hot paths, query a generated column, or store `jsonb(source)` in a BLOB column.

### 4\. Comments live only in your source column

Every function that returns JSON returns it stripped. A script that reads `json_set(source, ...)` and writes the result back to `source` silently deletes the comments. Write edits to the original text yourself, or edit a canonical copy and keep the source as a separate record.

### 5\. A stored generated column can change the error you see

With `doc TEXT AS (json(source)) STORED` in the table, a bad insert reported `malformed JSON` instead of the `CHECK` message in our test. If your code matches error strings, test the exact failure for your schema.

## JSON5 in SQLite: Common Questions

### Which SQLite version added JSON5?

3.42.0, released 2023-05-16. Earlier versions read only canonical JSON.

### Why does `json_valid('{x:1}')` return 0?

With one argument, the check means strict JSON (flag 1) for compatibility. Pass 2 for JSON5, or 6 to also accept JSONB.

### Can SQLite output JSON5?

No. Output is always strict JSON with no comments, quote style or number format preserved.

### Is SQLite a good JSON5 validator?

Not for strict checking. It accepts `Inf`, `QNaN` and wider Unicode keys than the specification allows. Use a [conforming parser](https://json5.dev/glossary/#conforming-parser); the [conformance page](https://json5.dev/conformance/) lists the options.

### Does it work with JSONB?

Yes. `jsonb(X)` accepted our JSON5 text in a test, and the stored blob passes `json_valid(X, 4)` and `json_valid(X, 8)`. The documentation says nothing more specific about JSON5 in JSONB, and JSONB output is not JSON5.

### Where else can I use JSON5 input?

See the [tools overview](https://json5.dev/tools/) for editors, the CLI and other integrations.

## Related Pages

[![Python logo](https://json5.dev/images/tech/python.png)

### Python Guide

Parse in the application instead

](https://json5.dev/python/)[![Convert icon](https://json5.dev/images/icons/convert.png)

### Conversion

JSON5 to JSON and back

](https://json5.dev/tools/conversion/)[![Specification icon](https://json5.dev/images/icons/spec.png)

### The Specification

What conforming parsers accept

](https://json5.dev/spec/)

## Sources

(5)

1.  [SQLite: JSON Functions And Operators](https://www.sqlite.org/json1.html) (sections on JSON arguments, JSON5 extensions, `json_valid` and `json_error_position`)
2.  [SQLite release 3.42.0 (2023-05-16)](https://www.sqlite.org/releaselog/3_42_0.html)
3.  [SQLite: Generated Columns](https://www.sqlite.org/gencol.html)
4.  [SQLite: Indexes On Expressions](https://www.sqlite.org/expridx.html)
5.  [The JSON5 specification](https://spec.json5.org/) (numeric literal grammar)

Last reviewed: November 29, 2026.
