JSON 对象为 null 但不知为何它的子对象不是?

JSON object is null but somehow its children are not?

我对以下明显的矛盾感到有点困惑:

select json_extract_scalar('{"json_array":[{"array_field":"1"}]}', 
                           '$.json_array') is null,
       json_extract_scalar('{"json_array":[{"array_field":"1"}]}', 
                           '$.json_array[0]') is null,
       json_extract_scalar('{"json_array":[{"array_field":"1"}]}', 
                           '$.json_array[0].array_field') is null

结果:

true  true false

怎么可能 json_arrayNULL,但是在进一步挖掘时突然返回非空?

这是因为您使用了 json_extract_scalar 而不是 json_extractjson_extract_scalar returns 标量(不像数组或对象那样复合)或 NULL,如果 json 路径的目标不是标量。

比较这些表达式。区别在于一个使用 json_extract_scalar 而另一个使用 json_extract:

presto> select json_extract_scalar('{"json_array":[{"array_field":"1"}]}', '$.json_array'),
     -> json_extract('{"json_array":[{"array_field":"1"}]}', '$.json_array');
 _col0 |         _col1
-------+-----------------------
 NULL  | [{"array_field":"1"}]
(1 row)