Querying JSON with SQLite

Featured image for sharing metadata for article

I really like the fact that a lot of the database engines are allowing for native JSON querying, not least with SQLite, as I'm using it for various projects at the moment.

However, I can never seem to remember the incantation for how to actually perform the JSON query.

Let's say that we have the following schema and data:

CREATE TABLE data (
  id integer PRIMARY KEY,
  json TEXT,
  array TEXT
);

INSERT INTO data (json, array) VALUES('
{
  "name": "go",
  "depTypes": [
    "require",
    "indirect"
  ]
}',
  '[ "require", "indirect" ]'
);

INSERT INTO data (json, array) VALUES('
{
  "name": "ruby",
  "depTypes": [
    "dev"
  ]
}',
  '[ "dev" ]'
);

If we wanted to parse our array type, we could query:

select data.id, arr.value from data, json_each(data.array) as arr;

And if we wanted to query a JSON field within json, we could query:

select id, json_extract(data.json, '$.name') name from data;

And to query the depTypes array within json:

select data.id, depType.value from data, json_each(json_extract(data.json, '$.depTypes')) depType;

Written by Jamie Tanna's profile image Jamie Tanna on , and last updated on .

Content for this article is shared under the terms of the Creative Commons Attribution Non Commercial Share Alike 4.0 International, and code is shared under the Apache License 2.0.

#blogumentation #sqlite #json.

This post was filed under articles.

Interactions with this post

Interactions with this post

Below you can find the interactions that this page has had using WebMention.

Have you written a response to this post? Let me know the URL:

Do you not have a website set up with WebMention capabilities? You can use Comment Parade.