2014-11-05 97 views
1

Postgres中有这种方法吗?从Postgres中的JSON数组中选择

SELECT * FROM magic_json_function('[{"col1": 1, "col2": "A"}, {"col1": 2, "col2": "B"}]') 

col1 | col2 
------+------ 
1 | A 
2 | B 
(2 rows) 

编辑:,而无需创建一个表。

回答

2

这是我最后只是:

SELECT value->>'col1' AS col1, value->>'col2' AS col2 
FROM json_array_elements('[{"col1": 1, "col2": "A"}, {"col1": 2, "col2": "B"}]') 

col1 | col2 
------+------ 
1 | A 
2 | B 
(2 rows) 
+0

不错的一个。永远不会想到它;) – 2014-11-05 22:37:56

3

当然,功能json_populate_recordset。假设有通过

CREATE TABLE test(
    col1 int, 
    col2 text 
); 

定义的表test你可以简单:

SELECT * FROM json_populate_recordset(NULL::test,'[{"col1": 1, "col2": "A"}, {"col1": 2, "col2": "B"}]') 
+0

而不是'CREATE TABLE',你也可以使用'CREATE TYPE' – 2014-11-06 10:24:30