1

I have employee table in postgreSQL

CREATE TABLE Employee(EmployeeID integer PRIMARY KEY AUTO_INCREMENT,
Employeename VARCHAR(100));

alter table Employee add column parents JSON;

Now, I want to update JSON column with JSON array with a value from the existing column like below.

update employee set parents = json_array_elements('[{"name":Employeename, "id":EmployeeID }]')

Any way I can achieve this?

2 Answers 2

1

Try using:

  • JSON_BUILD_OBJECT function, to generate your json element
  • JSON_BUILD_ARRAY function, to enclose your json object into an array
UPDATE employee 
SET parents = JSON_BUILD_ARRAY(
                  JSON_BUILD_OBJECT('name', Employeename, 
                                    'id'  , EmployeeID   ));

Check the demo here.


If you need to store it as an array, since

Sign up to request clarification or add additional context in comments.

4 Comments

I need this as JSON array not object
What's the purpose of having an array when the object is only one? What are you aggregating on?
I will get updates in time to add several other objects
Nesting json_build_object into json_build_array should do it. Try the demo now.
0

if parents is json[]

UPDATE employee 
SET parents = array[
                  JSON_BUILD_OBJECT('name', Employeename, 
                                    'id'  , EmployeeID   )]::json[];

https://stackoverflow.com/a/35081935/1025379

Comments

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.