我必须从包含空间信息的json文件中提取数据。该文件的内容是
create table field(data json);
COPY field(data) FROM '/home/guest-pc5/field.json';
我创建了一个表,然后将该文件的内容复制到其中
SELECT json_array_elements(data->'vertices') from field;
{"lat":46.744628268759314,"lon":6.569952920654968}
{"lat":46.74441692818192,"lon":6.570487107359068}
{"lat":46.74426116111054,"lon":6.570355867853787}
{"lat":46.74447250168793,"lon":6.569821681149689}
(4 rows)
我现在可以查询我的数据
了 select * from json_to_recordset('[{"lat":46.744628268759314,"lon":6.569952920654968},{"lat":46.74441692818192,"lon":6.570487107359068},{"lat":46.74426116111054,"lon":6.570355867853787},{"lat":46.74447250168793,"lon":6.569821681149689}]') as (lat numeric, lon numeric);
ERROR: function json_to_recordset(unknown) does not exist
LINE 1: select * from json_to_recordset('[{"lat":46.744628268759314,...
^
HINT: No function matches the given name and argument types. You might need to add explicit type casts.
问题在于我无法像那样使用它。我想只捕获“lat”和“lon”的值,将它们放在字段表中
我试图使用函数json_to_recordset但没有成功
FnMut
答案 0 :(得分:1)
您可以使用json manipulator operator ->>
从json_array_elements
输出中获取所需的值作为文本。为方便起见,您可以在json_array_elements
子句中调用FROM
(这是对lateral的set-returning function次调用):
SELECT
f.data AS original_json,
CAST((e.element->>'lat') AS numeric) AS lat,
CAST((e.element->>'lon') AS numeric) AS lon
FROM
field AS f,
json_array_elements(f.data->'vertices') AS e(element);
通过它,您可以简单地创建一个表(或将INSERT用于现有表):
CREATE TABLE coordinates AS
SELECT
f.data AS original_json,
CAST((e.element->>'lat') AS numeric) AS lat,
CAST((e.element->>'lon') AS numeric) AS lon
FROM
field AS f,
json_array_elements(f.data->'vertices') AS e(element);
OBS:LATERAL是隐式的,因为LATERAL关键字对于集合返回函数调用是可选的,但你可以使它真正明确,如:
FROM
field f
CROSS JOIN LATERAL json_array_elements(f.data->'vertices') AS e(element);
此外,LATERAL仅为9.3+,尽管您使用json_array_elements
时肯定高于此值(仅限9.3+)。