Querying json in postgres

前端 未结 1 662
忘掉有多难
忘掉有多难 2021-01-20 16:26

I have to extract data from a json file who contains spatial information. The content of this file is

{\"vertices\":[{\"lat\":46.744628268759314,\"lon\":6.56         


        
1条回答
  •  隐瞒了意图╮
    2021-01-20 17:24

    You can use json manipulator operator ->> to get the value you want as text out of json_array_elements output. To make it easier, you can call json_array_elements in FROM clause (which is a lateral call to a 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);
    

    With that, you can simple create a table (or use INSERT into an existent one):

    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: The LATERAL there is implicit, as the LATERAL keyword is optional for set-returning function calls, but you could make it really explicit, as:

    FROM
        field f
        CROSS JOIN LATERAL json_array_elements(f.data->'vertices') AS e(element);
    

    Also, LATERAL is 9.3+ only, although you are certainly above that as you are using json_array_elements (also 9.3+ only).

    0 讨论(0)
提交回复
热议问题