Answer the question
In order to leave comments, you need to log in
How to add value to jsonb array postgresql 9.6?
There is a table. The table has an abilities field of jsonb type, which has the default:
{
"craft" : [],
"combat" : [],
"harvest" : []
}
Each of these arrays should consist of skill ids and look something like this:
{ " harvest" : [ ["id", "lvl"],["id", "lvl"],["id", "lvl"] ], "craft" : [ ["id", "lvl"], ["id", "lvl"],["id", "lvl"] ] }
How can I add and remove values to these arrays? Is there some kind of object oriented functionality for simple change access to the values of nested objects?
Additional question:
There is an inventory field of type jsonb[], default is null. It must accept {...} objects, which must be array elements of this field. How to add and remove objects in this case? How to edit the properties of each individual object? For example, an object has fields { "id": 1, "name": goldcoin, "count": 20 }. I want to change the count inside this object, the way it will be the first value of this table field. I also want to add an object { "id": 2, "name": sword, "count": 1} to this field or delete the same object
Answer the question
In order to leave comments, you need to log in
in your case, in the case of working with an object, you can go this way:
DO
$$
DECLARE
objectOrigin jsonb;
objectModingCount jsonb;
objectModingCraft jsonb;
arrayCraft jsonb;
BEGIN
objectOrigin = '{"craft":[], "count":0}'::jsonb;
arrayCraft = objectgetvaluearray(objectOrigin, 'craft', '[]');
arrayCraft = arraypushstring(arrayCraft, 'string');
arrayCraft = arraypushnumber(arrayCraft, '1234567890');
arrayCraft = arraypushboolean(arrayCraft, 'true');
arrayCraft = arraypushobject(arrayCraft, '{}');
arrayCraft = arraypusharray(arrayCraft, '[]');
objectModingCount = objectsetvaluenumber(objectModingCount, 'count', 2);
objectModingCraft = objectsetvaluearray(objectModingCraft, 'craft', arrayCraft);
objectOrigin = objectOrigin || objectModingCount || objectModingCraft;
RAISE NOTICE '%', objectOrigin;
END;
$$
LANGUAGE plpgsql;
NOTICE: {"count": 2, "craft": ["string", 1234567890, true, {}, []]}
CONTEXT: PL/pgSQL function inline_code_block line 21 at RAISE
query result (line 1) discarded.
Query returned successfully with no result in 18 msec.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question