乐闻世界logo
搜索文章和话题

How to use SQLite's JSON extension?

2月18日 21:50

SQLite's JSON extension provides the ability to process JSON data:

  1. 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
  2. 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()
  3. 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"]
  4. 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"
  5. 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"}
  6. 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
  7. 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';
  8. JSON Path Expressions

    • $: Root object
    • .key: Object property
    • [index]: Array index
    • *: Wildcard
    • ..: Recursive descent
  9. Performance Considerations

    • JSON queries are slower than direct column queries
    • Can use generated columns and indexes to optimize JSON queries
    sql
    CREATE 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);
  10. 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.

标签:Sqlite