Course contentsShow
← Databases & SQL
Lesson 1116 of 1,95310. Embedded and Lightweight DatabasesFree lesson

JSON Data Handling in SQLite

Query and manipulate nested JSON structures stored within individual database columns.

In this lesson, you will learn how to query and manipulate deeply nested JSON structures stored within individual SQLite columns to retrieve or modify specific data points without needing to parse the entire object in your application code.

Navigating JSON Structures

SQLite treats JSON stored in text columns as a first-class citizen using its built-in JSON1 extension. To access nested data, we use the json_extract() function. This function uses a "path" syntax where $ represents the root of the JSON document.

Imagine you have a table named devices with a column config containing: {"network": {"ip": "192.168.1.1", "ports": [80, 443]}}

To extract the IP address, you point to the nested key:

SELECT json_extract(config, '$.network.ip') AS ip_address 
FROM devices;

Accessing Arrays

When dealing with nested arrays, you can index them directly. For example, to retrieve the first port (index 0) from that same JSON object, you would use:

SELECT json_extract(config, '$.network.ports[0]') AS primary_port 
FROM devices;

Modifying Nested Data

Updating nested data is just as straightforward using json_set(). This function takes the JSON column, the path to modify, and the new value. Importantly, json_set() will create the path if it doesn’t exist or overwrite it if it does:

UPDATE devices 
SET config = json_set(config, '$.network.ip', '10.0.0.1')
WHERE id = 1;

Why This Matters for Embedded Systems

In embedded environments, memory is a premium resource. Instead of fetching a large JSON string into your application layer to extract a single configuration value, you offload the processing to the database engine. This reduces data transfer between the database and your host application, keeping your memory footprint small and your performance snappy. You can even create an index on a specific expression like json_extract(config, '$.network.ip') to make searches across these nested structures incredibly fast.

Key Takeaway: Use SQLite’s json_extract and json_set to treat nested JSON fields like traditional columns, allowing for efficient, in-place manipulation of complex data structures without the overhead of external parsing.