Anyquery is not strictly normalized. It can handle JSON arrays and objects in columns. Those are stored as text and can be queried using JSON functions. Most plugins return JSON data, so it’s essential to know how to work with them.
Arrays
Let’s say we have a product table with a column containing an array of tags:
CREATETABLEproducts (
id INTEGERPRIMARY KEY,
nameTEXT,
tags TEXT
);
id
name
tags
1
Apple
[“fruit”, “red”, “sweet”]
2
Carrot
[“vegetable”, “orange”, “healthy”]
Calculating the number of tags
To calculate the number of tags for each product, you can use the json_array_length function:
To extract a field from the JSON object, you can use the json_extract function or its shorthand ->>. You need to provide a JSON path. The object is referenced by $. To access a field, use $.<field>. And for an array, use $[<index>]. To get all elements of an array, use $[*].
SELECTname, properties->>'$.color'AS color
FROM products2;
-- Equivalent to:
SELECTname, json_extract(properties, '$.color')AS color
FROM products2;
name
color
Apple
red
Carrot
orange
Extracting an array
Similarly, you can extract an array from the JSON object:
SELECTname, valueAS tag
FROM products2, json_each(properties->'$.tags');
name
tag
Apple
fruit
Apple
red
Apple
sweet
Carrot
vegetable
Carrot
orange
Carrot
healthy
Ensuring a field exists
To ensure a field exists in the JSON object, you can use the json_has function: