I have a table with a field of type JSON. The JSON field contains a JSON object with an array. How do I query the length of this array for each row?
class Post(Base):
__tablename__ = 'posts'
id = Column(Integer, primary_key=True)
items = Column(JSON)
Example rows in this table:
id: 1, items: [2,3,5]
id: 2, items: [2,3,5, 8, 12]
id: 3, items: [2,5]
id: 4, items: []
Expected result:
1 3
2 5
3 2
4 0
Is there something like this:
session.query(Post.id, len(Post.items))
Note: The JSON field contains an array of complex objects, I have used integers here only for the purpose of illustration.
Found a solution
Create a class that extends FunctionElement like this
from sqlalchemy.sql.expression import FunctionElement
from sqlalchemy.ext.compiler import compiles
class json_array_length(FunctionElement):
name = 'json_array_len'
@compiles(json_array_length)
def compile(element, compiler, **kw):
return "json_array_length(%s)" % compiler.process(element.clauses)
and use it like this
session.query(Post.id, json_array_length(Post.items))
Note: this will work on postgres because the function 'json_array_length' is defined in it. If you want this for a different DB that function will need to change. Refer http://docs.sqlalchemy.org/en/rel_0_9/core/compiler.html#further-examples
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With