I have a postgres db with a json data field. The json I have is an array of objects:
[{"name":"Mickey Mouse","age":10},{"name":"Donald Duck","age":5}]
I'm trying to return values for a specific key in a JSON array, so in the above example I'd like to return the values for name.
When I use the following query I just get a NULL value returned:
SELECT data->'name' AS name FROM json_test
Im assuming this is because it's an array of objects? Is it possible to directly address the name key?
Ultimately what I need to do is to return a count of every unique name, is this possible?
Thanks!
you have to unnest the array of json-objects first using the function (
json_array_elements
orjsonb_array_elements
if you have jsonb data type), then you can access the values by specifying the key.To get a count of unique names, its a similar query to the above, except the count distinct aggregate function is applied to
y.x->>name
It is necessary to use
->>
instead of->
as the former (->>
) casts the extracted value as text, which supports equality comparison (needed for distinct count), whereas the latter (->
) extracts the value as json, which does not support equality comparison.Alternatively, convert the
json
asjsonb
and usejsonb_array_elements
.JSONB
supports the equality comparison, thus it is possible to use COUNT DISTINCT along with extraction via->
, i.e.You can use
jsonb_array_elements
(when usingjsonb
) orjson_array_elements
(when usingjson
) to expand the array elements.For example:
In this example,
sample_data_elements
is equivalent to a table with a singlejsonb
column calledelem
, with two rows (the two array elements in the initial data).The result consists of two rows (one
jsonb
column, or of typetext
if you used->>'name'
instead):You should them be able to group and aggregate as usual to return the count of individual names.
Do like this: