How can I insert into a Postgresql JSON array - json

The table definition is:
chat_id serial primary key, last_update timestamp, messages JSON[]
and I want to insert a record like this:
insert into chats (messages) values ('{{"sender":"pablo","body":"they are on to us"}}');
with error:
ERROR: malformed array literal: "{{"sender":"pablo","body":"they are on to us"}}"
LINE 1: insert into chats (messages) values ('{{"sender":"pablo","bo...
I have also tried this approach :
insert into chats (messages) values (ARRAY('{"sender":"pablo","body":"they are on to us"}'));
Note that updating the row and inserting with array_append works OK.

I think this is a clash between the JSON notation that starts with { and the short hand array notation in Postgres where the string representation of an array is also denoted by an {.
The following works:
insert into chats
(messages)
values
(array['{"sender":"pablo","body":"they are on to us"}']::json[]);
This avoids the ambiguity of the {{ by using an explicit array constructor.
To make the array a json array you need to either cast the string to a json or the resulting array to a json[] (see the example above). Casting the whole array makes it easier if you have more than one JSON document in that row:
insert into chats
(messages)
values
(array['{"sender":"pablo","body":"they are on to us"}',
'{"sender":"arthur"}']::json[]);
alternatively:
insert into chats
(messages)
values
(array['{"sender":"pablo","body":"they are on to us"}'::json,
'{"sender":"arthur"}'::json]);

It is quite complicate to escape special characters. I would use insert from select to make it easier.
Create JSON array.
Convert it to set of JSON variables.
Convert the set to SQL array.
The select part below.
WITH bu AS (SELECT json_array_elements('[{"name":"obj1"},{"name":"obj2"},{"name":"obj3"},{"name":"obj4"}]'::json) AS bu)
SELECT array_agg(bu) FROM bu;

Related

How to insert varchar into postgresql json column

I have been struggling in how to insert into a table in PG that has a JSON column...
I am extracting a bit column from another table, and now I want to insert that bit to the json column, for example:
INSERT INTO TABLE (JSON) VALUES( '{"IsAllowed":"' || is_allowed::TEXT || '"}'::JSON )
is_allowed represents to the bit from another table...
And I get:
"column "XXX" is of type json but expression is of type text"
Does anyone know how can I achieve this?
Thanks!
You should be using jsonb instead of json, but that is not part of your question.
PostgreSQL does not allow bidirectional casting between bit and boolean types. The same goes for bit and int.
Please try this:
insert into table (json) values
(json_build_object('IsAllowed', is_allowed = 1::bit));
Your command:
INSERT INTO TABLE (JSON) VALUES( '{"IsAllowed":"' || is_allowed::TEXT || '"}'::JSON )
is casting '"}' to JSON. Try adding some brackets:
INSERT INTO TABLE (JSON) VALUES( ('{"IsAllowed":"' || is_allowed::TEXT || '"}')::JSON )
Note: I could not replicate the error you are receiving (got "Token ""}" is invalid.") but with the brackets this worked fine.

mySql JSON string field returns encoded

First week having to deal with a MYSQL database and JSON field types and I cannot seem to figure out why values are encoded automatically and then returned in encoded format.
Given the following SQL
-- create a multiline string with a tab example
SET #str ="Line One
Line 2 Tabbed out
Line 3";
-- encode it
SET #j = JSON_OBJECT("str", #str);
-- extract the value by name
SET #strOut = JSON_EXTRACT(#J, "$.str");
-- show the object and attribute value.
SELECT #j, #strOut;
You end up with what appears to be a full formed JSON object with a single attribute encoded.
#j = {"str": "Line One\n\tLine 2\tTabbed out\n\tLine 3"}
but using JSON_EXTRACT to get the attribute value I get the encoded version including outer quotes.
#strOut = "Line One\n\tLine 2\tTabbed out\n\tLine 3"
I would expect to get my original string with the \n \t all unescaped to the original values and no outer quotes. as such
Line One
Line 2 Tabbed out
Line 3
I can't seem to find any JSON_DECODE or JSON_UNESCAPE or similar functions.
I did find a JSON_ESCAPE() function but that appears to be used to manually build a JSON object structure in a string.
What am I missing to extract the values to the original format?
I like to use handy operator ->> for this.
It was introduced in MySQL 5.7.13, and basically combines JSON_EXTRACT() and JSON_UNQUOTE():
SET #strOut = #J ->> '$.str';
You are looking for the JSON_UNQUOTE function
SET #strOut = JSON_UNQUOTE( JSON_EXTRACT(#J, "$.str") );
The result of JSON_EXTRACT() is intentionally a JSON document, not a string.
A JSON document may be:
An object enclosed in { }
An array enclosed in [ ]
A scalar string value enclosed in " "
A scalar number or boolean value
A null — but this is not an SQL NULL, it's a JSON null. This leads to confusing cases because you can extract a JSON field whose JSON value is null, and yet in an SQL expression, this fails IS NULL tests, and it also fails to be equal to an SQL string 'null'. Because it's a JSON type, not a scalar type.

oracle plsql json query return array, loop this array

I have a table with clob column and it contains json data,
I am trying to parse this, using JSON_query, one of the attribute in json data is array,
select JSON_query(v.json_sub_pojo,'$.systemAcronyms')
, v.*
from notf.ver v
returns
["ONE","TWO"]
I need help in loop the values of array.

retrieve json array as array without quotes in mysql

I am using json datatype in mysql to store array of numbers as ["9","10"] in a table
Then I do
select numbers from table WHERE id = 1
This return 'numbers' as ["9","10"] in console but when I try to access the array in the code it is shown as "[\"9\",\"10\"]"
I tried JSON_UNQUOTE but it returns "[\"9\",\"10\"]" the same result.
How do I get it as an array as ["9","10"] and not "[\"9\",\"10\"]"

querying json object from table in postgreSQL

I want to use where condition on a json object in a table, in postgreSql. how i need to do this for example: i have a table 'test' it has three columns name(varchar),url(varchar),more(json). i need to retrive date where css21Colors = Purple.
more is a json type and below is the values of more field.
Please let me know what should be syntax of querying for the same?
more = {"colorTree":{"Purple":[{"Spanish Violet":"#522173"}],
"Brown":[{"Dark Puce":"#4e3347"}],"White":[{"White":"#ffffff"}],
"Black":[{"Eerie Black":"#1d0d27"}],"Gray":[{"Rose Quartz":"#a091a4"}]},
"sizeoutscount":0,"css21Colors":{"Purple":69,"Brown":5,"White":4,"Black":17,"Gray":3},
"sizeins": [],"sizeinscount":0,"sizeouts":[],"allsizes":["8","10","16"],
"css3Colors": {"Rose Quartz":3,"White":4,"Dark Puce":5,"Eerie Black":17,"Spanish
Violet":69},"hexColors":{"#522173":69,"#4e3347":5,"#ffffff":4,"#1d0d27":17,"#a091a4":3}}
SELECT more->'css21Colors'->'Purple' FROM test;
Additionally you can query only the rows containing that key.
SELECT
more->'css21Colors'->'Purple'
FROM
test
WHERE
(more->'css21Colors')::jsonb ? 'Purple';
Mind switching to the jsonb data type.