2

So l have been trying to find an answer on the internet with 0 luck.

Does postgres support having arrays of objects in a single field, e.g.

[
  {
    key: value,
    another: value
  },
  {
    key: value,
    value: key
  }
 ]

and saving this to a single field?

Also how would you perform the single INSERT or UPDATE

would it be: UPDATE db SET value='[{ key: val }, { key: val }]' ??

1
  • 3
    json[] would be an array of documents. You are looking for a document that contains an array - yes that is possible with json Commented Feb 2, 2016 at 22:51

2 Answers 2

1

Postgres supports any valid json values, including json arrays. What you are going to use is a single json (jsonb) column, not a Postgres array:

create table example (id int, val jsonb);
insert into example
values (1, '[{ "name": "aga" }, { "gender": "female" }]');

select * from example;

 id |                   val                   
----+-----------------------------------------
  1 | [{"name": "aga"}, {"gender": "female"}]
(1 row) 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the quick answer!
1

It depends on your definitoion of objects I guess.

You can use JSON: http://www.postgresql.org/docs/current/static/functions-json.html and insert unstructured data:

# create table test (field json);
CREATE TABLE
# insert into test values ('[1,2,3]');
INSERT 0 1
# insert into test values ('[{"key": "value"}, {"key": "value"}]');
INSERT 0 1
# select * from test;
                field                 
--------------------------------------
 [1,2,3]
 [{"key": "value"}, {"key": "value"}]

There is also support for arrays: http://www.postgresql.org/docs/current/static/arrays.html

1 Comment

Cheers for the answer!

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.