SQLite's JSON extension provides the ability to process JSON data:
-
JSON Extension Overview
- SQLite 3.38.0+ has built-in JSON1 extension
- Provides a set of functions for creating, querying, and manipulating JSON data
- JSON data is stored in the database as TEXT type
-
JSON Function Categories
- Creation Functions: json_array(), json_object()
- Extraction Functions: json_extract(), json_each()
- Modification Functions: json_set(), json_remove()
- Query Functions: json_array_length(), json_type()
- Path Functions: json_patch(), json_tree()
-
Creating JSON Data
sql-- Create JSON object SELECT json_object('name', 'Alice', 'age', 30); -- Output: {"name":"Alice","age":30} -- Create JSON array SELECT json_array(1, 2, 3, 'four'); -- Output: [1,2,3,"four"] -
Extracting JSON Data
sql-- Extract JSON field SELECT json_extract('{"name":"Alice","age":30}', '$.name'); -- Output: "Alice" -- Extract nested field SELECT json_extract('{"user":{"name":"Alice"}}', '$.user.name'); -- Output: "Alice" -
Modifying JSON Data
sql-- Set or update JSON field SELECT json_set('{"name":"Alice"}', '$.age', 30); -- Output: {"name":"Alice","age":30} -- Remove JSON field SELECT json_remove('{"name":"Alice","age":30}', '$.age'); -- Output: {"name":"Alice"} -
Querying JSON Data
sql-- Get JSON array length SELECT json_array_length('[1,2,3,4]'); -- Output: 4 -- Get JSON field type SELECT json_type('{"name":"Alice","age":30}', '$.age'); -- Output: integer -
Using JSON in Tables
sql-- Create table with JSON field CREATE TABLE users ( id INTEGER PRIMARY KEY, data TEXT ); -- Insert JSON data INSERT INTO users (data) VALUES (json_object('name', 'Alice', 'tags', json_array('admin', 'user'))); -- Query JSON data SELECT json_extract(data, '$.name') as name FROM users; -- Filter based on JSON field SELECT * FROM users WHERE json_extract(data, '$.name') = 'Alice'; -
JSON Path Expressions
$: Root object.key: Object property[index]: Array index*: Wildcard..: Recursive descent
-
Performance Considerations
- JSON queries are slower than direct column queries
- Can use generated columns and indexes to optimize JSON queries
sqlCREATE TABLE users ( id INTEGER PRIMARY KEY, data TEXT, name TEXT GENERATED ALWAYS AS (json_extract(data, '$.name')) STORED ); CREATE INDEX idx_name ON users(name); -
Use Cases
- Store flexible data structures
- Store configuration information
- Store logs and metadata
- Implement NoSQL-style data storage
JSON extension enables SQLite to handle semi-structured data, enhancing database flexibility.