1

I'm trying to populate a new JSON field with existing data and could use some help getting the field properly formatted. I have a subquery returning a list of values intended to be an array in the JSON property. The subquery returns the right results but I can't quite get the JSON array populated properly.

My query is essentially this:

UPDATE foos SET json_property =  
cast(
  '{"bar_ids":' || 
  (select json_agg(x) from (select id from bars) x) || 
  '}'
as json);


What I want to store is this:

{"bar_ids":[1,2,3,4]}

but what I currently get is this:

{"bar_ids":[{"id":1},{"id":2},{"id":3},{"id":4}]}

Thoughts?

1 Answer 1

1

It seems that one subquery is needless:

UPDATE foos SET json_property =  
CAST(
  '{"bar_ids":' || 
  (SELECT JSON_AGG(x.id) FROM bars x) || 
  '}'
AS json);
Sign up to request clarification or add additional context in comments.

1 Comment

Ah, yeah, you're right. That nested subquery was the closest working thing I had after tossing stuff against the wall for a while. I yanked that out in my real query and it's working like a charm now!

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.