1

I have a column named data and I have to update its content from something like {} to [{}] for each record in table A, I tried to use JSON_ARRAY() but it gives me a quoted

["{\"something\": \"true\"}"]

but I'd like to have something like

[{ "something": "true" }]

How I do it now?

SELECT JSON_ARRAY(data) FROM A;

How should I update it either using JSON_SET() or UPDATE?

2 Answers 2

2

Try using

SELECT JSON_ARRAY_AGG(JSON_OBJECT(data)) from A;
Sign up to request clarification or add additional context in comments.

2 Comments

This will combine all the rows into a single array.
Yes it does. This isn't what I was looking for but thanks.
1

You need to use a path to get the data as JSON, rather than referring to the column by itself. The path $ means the top-level object.

update A 
SET data = CASE
    WHEN data IS NULL THEN '[]' -- NULL becomes empty array
    WHEN LEFT(data, 1) = '[' THEN data -- leave existing array alone
    ELSE JSON_ARRAY(data->"$") -- put object inside array
END

DEMO

9 Comments

Great, how can I apply it using a UPDATE? UPDATE A SET data=JSON_ARRAY(data->"$") WHERE data IS NOT NULL
Great answer. How can I add another condition to prevent running it twice? Like if data is alreay an array?
You can use a string function like and LEFT(data, 1) != '['
I missed to ask if the column is null is it possible to create an empty array for that? I used UPDATE cpdc SET cpdcFormData = JSON_ARRAY() WHERE cpdcFormData IS NULL But didn't work.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.