Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert the given JSON data to a table format in PostgreSQL

I am trying to convert JSON data to table format in PostgreSQL based on the given JSON. What I have done is below. Based on the given JSON data, I create the following table,

CREATE TABLE example_data (
    service_status TEXT,
    data_status TEXT,
    data_message TEXT,
    id INT,
    name TEXT,
    age INT
);

Use the json_populate_recordset function to insert the JSON data into the table.

INSERT INTO example_data (service_status, data_status, data_message, id, name, age)
SELECT 
    json_data->>'serviceStatus' AS service_status, 
    json_data->>'data.status' AS data_status, 
    json_data->>'data.message' AS data_message, 
    item->>'id' AS id, 
    item->>'name' AS name, 
    item->>'age' AS age
FROM (
    SELECT '{"serviceStatus": "OK", "data": {"status": "OK", "message": "", "item": [{"id": 1, "name": "John", "age": 30},{"id": 2, "name": "Smith", "age": 40}]}}'::json AS json_data
) AS data
CROSS JOIN LATERAL json_populate_recordset(NULL::example_data, json_data->'data'->'item') AS item;

Above query only returning the data in serviceStatus and all other fields are returning null. Can you help me where I am doing wrong. Thanks

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This one works, it’s using the correct json paths and using the table layout that you defined in example_data:

SELECT 
    json_data->>'serviceStatus' AS service_status, 
    json_data->'data'->>'status' AS data_status, 
    json_data->'data'->>'message' AS data_message, 
    item.id, -- this not json anymore
    item.name,
    item.age
FROM (
    SELECT '{"serviceStatus": "OK", "data": {"status": "OK", "message": "", "item": [{"id": 1, "name": "John", "age": 30},{"id": 2, "name": "Smith", "age": 40}]}}'::json AS json_data
) AS data
CROSS JOIN LATERAL json_populate_recordset(NULL::example_data, json_data->'data'->'item') AS item;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading