1

Is there a way to do this in Postgres?

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

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

Edit: Without having to create a table.

2 Answers 2

3

Sure, the function is json_populate_recordset. Assuming there's a table test defined by

CREATE TABLE test(
  col1 int,
  col2 text
);

You can simply:

SELECT * FROM json_populate_recordset(NULL::test,'[{"col1": 1, "col2": "A"}, {"col1": 2, "col2": "B"}]')
Sign up to request clarification or add additional context in comments.

1 Comment

Instead of CREATE TABLE you can also use CREATE TYPE
2

This is how I ended up doing it:

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)

1 Comment

nice one. never would thought of it ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.