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

PostgreSQL JSON array value from another column

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?

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 :

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

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