Skip to content
Advertisement

Extract JSON content in Metabase SQL query

Using: Django==2.2.24, Python=3.6, PostgreSQL is underlying DB
Working with Django ORM, I can easily make all sort of queries, but I started using Metabase, and my SQL might be a bit rusty.

The problem:
I am trying to get a count of the items in a list, under a key in a dictionary, stored as a JSONField:

Example of the dictionary stored in data_field:

Under "my_list" key, the value stored is a list, which contains a number of other dictionaries.
In Metabase, I am trying to get a count for the number of dictionaries in the list, but even more basic things, none of which work.

Some stuff I tried:
Attempt:

Error:

Attempt:

Error:

Attempt:

Error:

Attempt:

Error:

Basically, I think the issue is that I am using the wrong signatures (most of the time) in the methods I am trying to use.

I used this query to make sure I can at least get the keys from the dictionary:

I was not able to use JSON_OBJECT_KEYS() without adding the ::json cast, I was getting this error:

But with the json cast, I am getting all the keys as intended.


Thank you for taking a look!


EDIT:
I also found this interesting article with different solution but none of the solutions worked.
Also seen this SO post which did not help.

Advertisement

Answer

Ok, after some more digging around, I found this article, which had the correct format/syntax.

This code is what I used to fetch the list from the JSON object successfully:

Then, I used json_array_length() to get the number of elements:

All done! 🙂

EDIT:
I just found the reason to this whole shenanigan. In the code (which goes years back) we used this package:

And used this way:

The issue is that in the background, Postgres saves the data as a string, so it needs to be cast into a JSON. Later Django introduced its own JSONField, which stores data as you would expect, without a need to cast:

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement