json 上的 Postgres 查询具有空值

Postgres query on json with empty value

我在 JSON 中有一个查询,以根据 JSON 字段中存在的数据过滤掉数据。

Table 姓名:audit_rules 列名:rule_config (json)

rule_config 包含 JSON 其中包含 'applicable_category' 作为其中的属性。

例子

{
   "applicable_category":[
      {
         "status":"active",
         "supported":"yes",
         "expense_type":"Meal",
         "acceptable_variation":0.18,
         "minimum_value":25.0
      },
      {
         "status":"active",
         "supported":"yes",
         "expense_type":"Car Rental",
         "acceptable_variation":0.0,
         "minimum_value":25.0
      },
      {
         "status":"active",
         "supported":"yes",
         "expense_type":"Airfare",
         "acceptable_variation":0.0,
         "minimum_value":75
      },
      {
         "status":"active",
         "supported":"yes",
         "expense_type":"Hotel",
         "acceptable_variation":0.0,
         "minimum_value":75
      }
   ],
   "minimum_required_keys":[
      "amount",
      "date",
      "merchant",
      "location"
   ],
   "value":[
      0,
      0.5
   ]
}

但有些行没有任何数据或其中没有 'applicable_category' 属性。

所以在 运行 查询后我收到错误:

select s.*,j from 
  audit_rules  s 
   cross join lateral json_array_elements ( s.rule_config#>'{applicable_category}' ) as j
WHERE j->>'expense_type' in ('Direct Bill');

Error: SQL Error [22023]: ERROR: cannot call json_array_elements on a scalar

您可以将结果限制为仅包含数组的行:

select j.*
from audit_rules  s 
   cross join lateral json_array_elements(s.rule_config#>'{applicable_category}') as j
WHERE json_typeof(s.rule_config -> 'applicable_category') = 'array'
  and j ->> 'expense_type' in ('Meal')