Sign up ×
Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. It's 100% free, no registration required.

I have table where one of the fields is JSON array. I need to append received JSON array into that field without overriding existing values.

Something like that:

CREATE OR REPLACE FUNCTION add_array(
    array_received json[])
  RETURNS void AS
$BODY$

    update table set _array_field = _array_field | array_received ...;

$BODY$
  LANGUAGE plpgsql VOLATILE;
share|improve this question

1 Answer 1

up vote 0 down vote accepted

I did it with plv8 language. For windows users get packages from

http://www.postgresonline.com/journal/archives/305-PostgreSQL-9.3-extension-treats-for-windows-users-plV8.html

Then run this command

CREATE EXTENSION plv8

This is the function

CREATE OR REPLACE FUNCTION jsonarray_append(row_id bigint, append json[]) RETURNS void AS $$

    var json_array = [];

    var json_result = plv8.execute('select json_array_field from sometable where _id=$1',[row_id]);

    if(json_result[0].json_array_field != null){
        for(var i=0; i < append.length; i++){
            json_result[0].json_array_field .push(append[i]);
        }
        json_array = json_result[0].json_array_field;
    }
    else{
        json_array = append;
    }


    plv8.execute('update sometable set json_array_field = $1 where _id=$2', [json_array, row_id]);

$$ LANGUAGE plv8 IMMUTABLE STRICT;
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.