3

In following JSON structure,

[
 ["a", 921],
 ["b", ""],
 ..
 ... 
 ["c", null],
]

how to count occurrence of

  1. blank value ""

  2. null value

asked Jan 20, 2020 at 17:09

1 Answer 1

3

You can use the function json_array_elements to convert your array into a set of elements. Each element is itself an array, so you can use the -> operator to retrieve the second element. Once you have them, use a standard count(*), with the corresponding FILTER.

You can do it with the following SQL statement (the WITH helps you view the "step-by-step" approach):

WITH original_data(var) AS
(
 VALUES (
 '
 [
 ["a", 921],
 ["b", ""],
 ["c", null]
 ]
 '::json) -- Note the ::json to make sure PostgreSQL uses the proper type
)
, second_elements AS
(
SELECT 
 json_array_elements(var)->1 AS e
FROM
 original_data
)
SELECT
 count(e) AS total_elements,
 count(e) FILTER (WHERE e::text = '""') AS blank_elements,
 count(e) FILTER (WHERE e::text = 'null') AS null_elements
FROM
 second_elements ;

... or the following one:

SELECT
 count(e) AS total_elements,
 count(e) FILTER (WHERE e = '""') AS blank_elements,
 count(e) FILTER (WHERE e = 'null') AS null_elements
FROM
 (
 SELECT 
 (json_array_elements(var)->1)::text AS e
 FROM
 (
 VALUES (
 '
 [
 ["a", 921],
 ["b", ""],
 ["c", null]
 ]
 '::json)
 ) AS original_data(var)
) AS second_elements ;

In both cases, you get:

 total_elements | blank_elements | null_elements
 -------------: | -------------: | ------------:
 3 | 1 | 1

You can check everything at dbfiddle.

NOTE: If you want to use jsonb instead of json, just change the ::jsonwith ::jsonb in the first statement, and call the jsonb_array_elements instead of json_array_elements.

answered Jan 20, 2020 at 18:26

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.