Ask Your Question

Revision history [back]

PostgreSQL provides several built-in functions and operators for working with JSON data. One way to split a JSON column into separate columns for questions and answers is to use the JSON functions json_object_keys and json_extract_path_text.

Assuming your JSON data is stored in a column named json_data in a table named my_table, and the JSON has the following structure:

{
    "question1": "answer1",
    "question2": "answer2",
    "question3": "answer3"
}

You can split it into separate columns like this:

SELECT 
    json_data ->> 'question1' AS question1,
    json_data ->> 'question2' AS question2,
    json_data ->> 'question3' AS question3
FROM my_table;

This will create three separate columns with the names question1, question2, and question3, each containing the corresponding answer from the JSON data.

If the JSON structure is more complex and the questions and answers are nested within objects or arrays, you can use the json_object_keys function to get the keys of the top-level object, and the json_extract_path_text function to extract the values of the nested objects or arrays. Here's an example:

SELECT 
    json_data ->> 'name' AS name,
    json_extract_path_text(json_data -> 'questions', key1, 'question') AS question1,
    json_extract_path_text(json_data -> 'questions', key1, 'answer') AS answer1,
    json_extract_path_text(json_data -> 'questions', key2, 'question') AS question2,
    json_extract_path_text(json_data -> 'questions', key2, 'answer') AS answer2
FROM my_table, 
    json_object_keys(json_data -> 'questions') as key1,
    json_object_keys(json_data -> 'questions') as key2
WHERE key1 <> key2 AND key1 < key2;

In this example, the JSON data has a structure like this:

{
    "name": "John Doe",
    "questions": {
        "1": {
            "question": "What's your favorite color?",
            "answer": "Blue"
        },
        "2": {
            "question": "What's your favorite food?",
            "answer": "Pizza"
        }
    }
}

The SQL query extracts the name column from the top-level object, and uses the json_object_keys function to get the keys of the questions object. It then extracts the question and answer values from each nested object using the json_extract_path_text function, and returns them as separate columns.

Note that in this example, we use two copies of the json_object_keys function to generate all possible combinations of keys for the questions object, and filter out duplicate pairs using a WHERE clause. This is necessary because PostgreSQL does not provide a built-in function to iterate over object keys.