programing

json 필드 유형 postgresql에서 null 값을 쿼리하는 방법

javajsp 2023. 3. 10. 21:06

json 필드 유형 postgresql에서 null 값을 쿼리하는 방법

postgresql에 json 유형 필드가 있습니다.그러나 특정 필드가 null인 행을 선택할 수 없습니다.

코드:

SELECT *
FROM   json_array_elements(
  '[{"name": "Toby", "occupation": "Software Engineer"},
    {"name": "Zaphod", "occupation": "Galactic President"} ,
{"name2": "Zaphod", "occupation2": null} ]'  ) AS elem
where elem#>'{occupation2}' is null

이 조작은 정상적으로 동작합니다만, 다음의 에러가 표시됩니다.

ERROR:  operator does not exist: json #> boolean
LINE 6: where elem#>'{occupation2}' is null

라는 사실을 이용할 수 있다.elem->'occupation2'문자열 반환null타입의json다음과 같이 질문합니다.

select
    *
from  json_array_elements(
  '[{"name": "Toby", "occupation": "Software Engineer"},
    {"name": "Zaphod", "occupation": "Galactic President"} ,
    {"name2": "Zaphod", "occupation2": null} ]'
) as elem
where (elem->'occupation2')::text = 'null'

{"name2": "Zaphod", "occupation2": null}

값이 있는 모든 요소를 가져오려면nullJSON 또는 키가 존재하지 않는 경우 다음 작업을 수행할 수 있습니다.

select
    *
from  json_array_elements(
  '[{"name": "Toby", "occupation": "Software Engineer"},
    {"name": "Zaphod", "occupation": "Galactic President"} ,
    {"name2": "Zaphod", "occupation2": null} ]'
) as elem
where (elem->>'occupation2') is null

{"name": "Toby", "occupation": "Software Engineer"}
{"name": "Zaphod", "occupation": "Galactic President"}
{"name2": "Zaphod", "occupation2": null}

json-blob 내에서 null 값을 검색하는 경우 함수를 사용하는 것을 고려할 수 있습니다.json_typeof(json)Postgres 9.4에 소개되었습니다.

INSERT INTO table
  VALUES ('{ "value": "some", "object": {"int": 1, "nullValue": null}}');

SELECT * FROM table
  WHERE json_typeof(json->'object'->'nullValue') = 'null';

그러면 null 값에 대한 입력이 검색됩니다.

이게 도움이 됐으면 좋겠네요!

참고 자료: http://www.postgresql.org/docs/9.4/static/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE

여기에는 dbeaver 에디터를 사용합니다.이 에디터는 동작하고 있습니다.

SELECT * FROM json_array_elements('[{"name": "Toby", "occupation": "Software Engineer"},{"name": "Zaphod", "occupation": "Galactic President"},{"name2":"Zaphod","occupation2":null}]') AS elem
where elem#>'{occupation2}') IS NULL

@roman-pekar와 @mraxus의 답변은 도움이 되었지만, 정의되지 않은 것과 없는 것을 명확하게 구별할 수 있는 능력이 없어서 아쉬웠습니다.그래서 생각해낸 건

CREATE OR REPLACE FUNCTION isnull (element json)
RETURNS boolean AS $$
  SELECT (element IS NOT NULL) AND (element::text = 'null');
$$ LANGUAGE SQL IMMUTABLE STRICT;

select isnull('{"test":null}'::json->'test'); -- returns t
select isnull('{"test":"notnull"}'::json->'test'); -- returns f
select isnull('{"toot":"testundefined"}'::json->'test'); -- returns null

@a_horse_with_no_name도 추가 jsonb 연산자를 지적했습니다.?postgresql 버전 9.4에서 도입되었습니다.

SELECT '{"a":1, "b":2}'::jsonb ? 'b'

언급URL : https://stackoverflow.com/questions/19422640/how-to-query-for-null-values-in-json-field-type-postgresql