0

I'm trying to do select * from demo where demojson->'sub'->'item' = array("") but this doesn't work. I'd like to find the following

  • All rows where .sub.item in the JSON column is an array containing exactly one empty string ([""])
  • All rows where .sub.item in the JSON column is an array that may contain more than one item, but at least one of the items is an empty string. (["not empty", "also not empty", ""])

demojson column could contain for example

{ 
  "key": "value",
  "sub": {
    "item": [""]
  }
}
3
  • 2
    Please, show JSON file or a minimum sample. Commented Jan 17, 2017 at 17:56
  • Added an example. Commented Jan 17, 2017 at 18:27
  • I can't validate this text as a valid json file. jsonlint.com Commented Jan 17, 2017 at 20:33

3 Answers 3

1

Have you tried

SELECT * from demo 
WHERE demojson->'sub'->>'item' = '[""]';

Here ->> operator allows to get JSON object field as text.

And another solution

SELECT * from demo 
WHERE json_array_length(demojson->'sub'->'item') = 1 AND 
      demojson->'sub'->'item'->>0 = '';

Here ->> operators allows to get JSON first array element as text.

Sign up to request clarification or add additional context in comments.

2 Comments

Since you're not using any wildcards in your pattern, you probably want just = '[""]' and = '' rather than LIKE '[""]' and LIKE ''
@IMSoP Thanks for suggestion, it makes sense.
1

Due JSONLint doesn't validate the supplied text example, I've used the next:

CREATE TABLE info (id int, j JSON);
insert into info values 
  (1, '{"key":"k1", "sub": {"item":["i1","i2"]}}'),
  (2, '{"key":"k2", "sub": {"item":[""]}}'),
  (3, '{"key":"k3", "sub": {"item":["i2","i3"]}}');

Using the where clause in this way, it works:

select * from info
where j->'sub'->>'item' = '[""]';


+----+------------------------------------+
| id |                  j                 |
+----+------------------------------------+
|  2 | {"key":"k2", "sub": {"item":[""]}} |
+----+------------------------------------+

Can check it here: http://rextester.com/VEPY57423

Comments

1

Try the following:

SELECT * FROM demo
WHERE demojson->'sub'->'item' = to_jsonb(ARRAY['']);

Comments

Your Answer

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.