json-ize string column in postgresql - json

I have the following data structure:
create table test (tags VARCHAR, tags_json VARCHAR);
insert into test (tags, tags_json)
values ('A B', '["A", "B"]')
And I want to convert the column tags to a JSON column. If I were to do it with the tags_json column is pretty easy:
select tags_json::JSON from test
But when I run it using the tags column,
select tags::JSON from test
I get
SQL Error [22P02]: ERROR: invalid input syntax for type json
How can I convert the column tags to a JSON column in postgresql?

You need to first convert your "plain text" to an array, then you can use to_jsonb() to convert that to a proper JSON value:
select to_jsonb(regexp_split_to_array(tags, '\s+'))
from test;
If you want to permanently change the column's data type, you can use that expression in an ALTER statement:
alter table test
alter tags type jsonb
using to_jsonb(regexp_split_to_array(tags, '\s+'));

Related

How to select from MySQL where colmun is type text and data is json

Magento 2 table 'sales_order_payment' have column 'additional_information' which is in data type 'text'. Now data inside this field I see that is json (but as string - text)
{"raw_details_info":{"CustomerFirstname":"Mary",...
How can I select this as json?
I have try this. First I create view where I cast this column as json:
CREATE VIEW JSONTEST as SELECT cast(additional_information as json) as test FROM sales_order_payment;
Then I try to select this as json:
SELECT test->>'$.CustomerFirstname' from JSONTEST
But result is null. Any idea what is wrong?
Your path must start from the top of the document.
SELECT test->>'$.raw_details_info.CustomerFirstname' ...
Also the JSON stored in your TEXT column must be valid JSON, or else your cast will return an error. This is an advantage of the JSON data type in MySQL 5.7 and later, because it will require the content to be valid JSON.

Alter column varchar to json in psql

Hi i am trying to convert a column in my table from varchar to json and the table already had some string data. I tried doing that with the below command.
Database=# alter table table_name alter column message type json using
message::json;
But the command failed with the below error.
ERROR: invalid input syntax for type json
DETAIL: Token "This" is invalid.
CONTEXT: JSON data, line 1: This...
Note : The message column has a set of words with spaces like below.
"This is a message"
I am not sure what went wrong. Thanks in advance..
You can use to_jsonb() rather than casting:
alter table table_name
alter column message type jsonb using to_jsonb(message);
If you really want to use json (although jsonb is recommended), then cast the result back to a json type:
alter table table_name
alter column message type json using to_jsonb(message)::json;
But this seems rather strange for a column that doesn't contain "real" json values, only plain strings.
In my case, I wanna split varchar that have separator each n-character. For example
varchar "ab,cd,ef,gh" -> json ["ab","cd","ef","gh"]
First that I do, convert varchar into array with delimiter of comma (",")
ALTER table my_table ALTER column my_column TYPE text[] USING string_to_array(my_column,',')
Then, convert array of varchar into json (maybe will you use for GraphQL database)
ALTER table my_table ALTER column my_column TYPE json USING array_to_json(my_column)
That gives me a result of json(array) like ["ab","cd","ef","gh"]
You can simply run the following command below, it will surely convert the field type as well as the previous records, you might also need to update your models file of respective framework so you can work accordingly.
In my case, I was converting saves_states table's column named prev_month_access_counts type from text to json.
ALTER TABLE saved_states ALTER COLUMN prev_months_access_counts TYPE jsonb
using to_jsonb(prev_months_access_counts);

Save number or a string in json column without having to specify a key? Is this possbile?

Is it possible to store just a single number inside a json column in MySQL?
For example when I try to validate if this is a valid json
{55}
I get an error saying that this is not valid json.
How do I save a string or a number inside the json column without any key? I just want to store the value itself. Is this even possible?
You can just use a string representation of the number e.g.
create table test (j json);
insert into test values ('55');
select * from test
Output
55
Demo on dbfiddle
You can make the key equal to the value, for example - {"55":55}
or as suggested #lukasz-szozda use array type.
But you can’t exactly insert a keyless value(because of JSON standard )
You can just store the string representation of the number like:
insert into test (json_column) values ('55');
While
insert into test (json_column) values (55);
will fail raising an "Invalid JSON" error.
If you have the number stored in a variable, you will need to cast it to JSON or a valid JSON string. Assuming your number is stored in a user variable:
set #v = 55;
Then
insert into test (json_column) values (#v);
will fail.
But any of the following will work:
insert into test (json_column) values (cast(#v as json));
insert into test (json_column) values (cast(#v as char));
insert into test (json_column) values (concat(#v));
For this you need to create a column of type JSON
Then try to insert a value into that column, It will save as what you want.
eg:-
Create table query
create table my_json_table(val json);
Insert table query
insert into my_json_table (val) values ('55');
Please try this way. It will help you.

Talend Casting of JSON string to JSON or JSONB in PostgreSQL

I'm trying to use Talend to get JSON data that is stored in MySQL as a VARCHAR datatype and export it into PostgreSQL 9.4 table of the following type:
CREATE TABLE myTable( myJSON as JSONB)
When I try running the job I get the following error:
ERROR: column "json_string" is of type json but expression is of type
character varying
Hint: You will need to rewrite or cast the expression. Position:
54
If I use python or just plain SQL with PostgreSQL insert I can insert a string such as '{"Name":"blah"}' and it understands it.
INSERT INTO myTable(myJSON) VALUES ('{"Name":"blah"}');
Any Idea's how this can be done in Talend?
You can add a type-cast by opening the "Advanced Settings" tab on you "tPostgresqlOutput" component. Consider the following example:
In this case, the input row to "tPostgresqlOutput_1" has one column data. This column is of type String and is mapped to the database column data of type VARCHAR (as by the default suggested by Talend):
Next, open the component settings for tPostgresqlOutput_1 and locate the "Advanced settings" tab:
On this tab, you can replace the existing data column by a new expression:
In the name column, specify the target column name.
In the SQL Expression column, do your type casting. In this case: "?::json"`. Note the usage of the placeholder character?`` which will be replaced with the original value.
In Position, specify Replace. This will replace the value proposed by Talend with your SQL expression (including the type cast).
As Reference Column use the source value.
This should do the trick.
Here is a sample schema for where in i have the input row 'r' which has question_json and choice_json columns which are json strings. From which i know the key what i wanted to extract and here is how i do
you should look at the columns question_value and choice_value. Hope this helps you

PostgreSQL convert column_1 text[] type to column_2 json type

Is there a reasonably simple approach to copy column_1 (data type ttext[]) to column_2 (data type JSON)?
...or...
Is there a reasonably simple approach to directly convert a column's data type from text[] to JSON?
The table parts_bak1 I'm working with has two columns named material_size (text[]) and material_size_json (json).
I tried directly converting the column the following:
ALTER TABLE parts_bak1 ALTER COLUMN material_size TYPE JSON USING material_size::text[];
ERROR: column "material_size" cannot be cast automatically t
HINT: Specify a USING expression to perform the conversion.
I'm not sure how or even if I should approach the challenge using USING?
Input is welcome, this seems to work:
UPDATE parts_bak1
SET material_size_json = subq.material_size
FROM (SELECT id, array_to_json(material_size) AS material_size FROM parts_bak1) AS subq
WHERE parts_bak1.id=subq.id;