Postgres CROSS JOIN JSON_TO_RECORD,JSON_EACH

时间:2018-09-10 15:57:42

标签: json postgresql

我正在尝试使用Postgres生成以下输出

ONE    TWO      THREE
=====================
A1     A2       A3
B1     B2       B3

来自以下JSON

{"metadata" : { 
     "A" : { "one" : "A1" , "two" : "A2", "three" : "A3" }, 
     "B" : { "one" : "B1" , "two" : "B2", "three" : "B3" }
 }}

我有这个SQL语句

select *
  from JSON_TO_RECORD(value) as REC(ONE TEXT, TWO TEXT, THREE TEXT) 
 CROSS JOIN LATERAL JSON_EACH(
   '{"metadata" : { 
       "A" : { "one" : "A1" , "two" : "A2", "three" : "A3" }, 
       "B" : { "one" : "B1" , "two" : "B2", "three" : "B3" }
    }}'::json -> 'metadata');

在PSQL中执行时,我得到

ERROR:  column "value" does not exist
LINE 2:  from JSON_TO_RECORD(value) as REC(ONE TEXT, TWO TEXT, THREE...

我的理解是JSON_EACH输出包含2列(键和值)的结果集,我应该能够将值传递给JSON_TO_RECORD运算符。我在这里想念什么?

1 个答案:

答案 0 :(得分:3)

json_to_record(value)必须处于横向联接中,因为它使用了value中的json_each()

select rec.*
from json_each(
   '{"metadata" : { 
       "A" : { "one" : "A1" , "two" : "A2", "three" : "A3" }, 
       "B" : { "one" : "B1" , "two" : "B2", "three" : "B3" }
    }}'::json -> 'metadata')
cross join json_to_record(value) as rec(one text, two text, three text) 

 one | two | three 
-----+-----+-------
 A1  | A2  | A3
 B1  | B2  | B3
(2 rows)